/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.pocketsweet.chat.ui.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVCloud;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.FollowCallback;
import com.avos.avoscloud.FunctionCallback;
import com.avos.avoscloud.GetCallback;
import com.avos.avoscloud.SaveCallback;
import com.easemob.EMError;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMChatOptions;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.EMMessage.ChatType;
import com.easemob.chat.ImageMessageBody;
import com.easemob.chat.LocationMessageBody;
import com.easemob.chat.NormalFileMessageBody;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VideoMessageBody;
import com.easemob.chat.VoiceMessageBody;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.EMLog;
import com.easemob.util.PathUtil;
import com.easemob.util.VoiceRecorder;
import com.pocketsweet.C;
import com.pocketsweet.MLApplication;
import com.pocketsweet.MLCache;
import com.pocketsweet.MLContext;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.adapter.ExpressionAdapter;
import com.pocketsweet.chat.ui.adapter.ExpressionPagerAdapter;
import com.pocketsweet.chat.ui.adapter.MessageAdapter;
import com.pocketsweet.chat.ui.adapter.VoicePlayClickListener;
import com.pocketsweet.chatlib.controller.HXSDKHelper;
import com.pocketsweet.chatlib.controller.MolianContactManager;
import com.pocketsweet.chatlib.utils.ImageUtils;
import com.pocketsweet.chatlib.utils.SmileUtils;
import com.pocketsweet.chatui.Constant;
import com.pocketsweet.chatui.utils.CommonUtils;
import com.pocketsweet.chatui.widget.ExpandGridView;
import com.pocketsweet.chatui.widget.PasteEditText;
import com.pocketsweet.model.MLOrder;
import com.pocketsweet.model.MLReportRecord;
import com.pocketsweet.model.MLTestOrder;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.GiftStore;
import com.pocketsweet.ui.Recharge;
import com.pocketsweet.ui.Wallet;
import com.pocketsweet.ui.uilib.ActionItem;
import com.pocketsweet.ui.uilib.CountDownTimerView;
import com.pocketsweet.ui.uilib.CountDownTimerView.TimerListener;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.MyAlertDialog;
import com.pocketsweet.ui.uilib.TitlePopup;
import com.pocketsweet.ui.uilib.TitlePopup.OnItemOnClickListener;
import com.pocketsweet.ui.uilib.wheelview.WheelTimeContinued;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;

/**
 * 聊天页面
 */
public class ChatActivity extends BaseActivity implements OnClickListener,
        SensorEventListener {

    private static final int REQUEST_CODE_EMPTY_HISTORY = 2;
    public static final int REQUEST_CODE_CONTEXT_MENU = 3;
    private static final int REQUEST_CODE_MAP = 4;
    public static final int REQUEST_CODE_TEXT = 5;
    public static final int REQUEST_CODE_VOICE = 6;
    public static final int REQUEST_CODE_PICTURE = 7;
    public static final int REQUEST_CODE_LOCATION = 8;
    public static final int REQUEST_CODE_NET_DISK = 9;
    public static final int REQUEST_CODE_FILE = 10;
    public static final int REQUEST_CODE_COPY_AND_PASTE = 11;
    public static final int REQUEST_CODE_PICK_VIDEO = 12;
    public static final int REQUEST_CODE_DOWNLOAD_VIDEO = 13;
    public static final int REQUEST_CODE_VIDEO = 14;
    public static final int REQUEST_CODE_DOWNLOAD_VOICE = 15;
    public static final int REQUEST_CODE_SELECT_USER_CARD = 16;
    public static final int REQUEST_CODE_SEND_USER_CARD = 17;
    public static final int REQUEST_CODE_CAMERA = 18;
    public static final int REQUEST_CODE_LOCAL = 19;
    public static final int REQUEST_CODE_CLICK_DESTORY_IMG = 20;
    public static final int REQUEST_CODE_GROUP_DETAIL = 21;
    public static final int REQUEST_CODE_SELECT_VIDEO = 23;
    public static final int REQUEST_CODE_SELECT_FILE = 24;
    public static final int REQUEST_CODE_ADD_TO_BLACKLIST = 25;
    public static final int REQUEST_CODE_SELECT_GIFT = 26;//礼物request

    public static final int RESULT_CODE_COPY = 1;
    public static final int RESULT_CODE_DELETE = 2;
    public static final int RESULT_CODE_FORWARD = 3;
    public static final int RESULT_CODE_OPEN = 4;
    public static final int RESULT_CODE_DWONLOAD = 5;
    public static final int RESULT_CODE_TO_CLOUD = 6;
    public static final int RESULT_CODE_EXIT_GROUP = 7;

    public static final int CHATTYPE_SINGLE = 1;
    public static final int CHATTYPE_GROUP = 2;

    public static final String COPY_IMAGE = "EASEMOBIMG";
    private View recordingContainer;
    private ImageView micImage;
    private ImageView Chat_btn;
    private TextView recordingHint;
    private ListView listView;
    private PasteEditText mEditTextContent;
    private View buttonSetModeKeyboard;
    private View buttonSetModeVoice;
    private View buttonSend;
    private View buttonPressToSpeak;
    // private ViewPager expressionViewpager;
    private LinearLayout emojiIconContainer;
    private LinearLayout btnContainer;
    private LinearLayout callContent;
    private LinearLayout linGift;
    private Button btn_box;
    private View more;
    private int position;
    private ClipboardManager clipboard;
    private ViewPager expressionViewpager;
    private InputMethodManager manager;
    private List<String> reslist;
    private Drawable[] micImages;
    private int chatType;
    private EMConversation conversation;
    private NewMessageBroadcastReceiver receiver;
    public static ChatActivity activityInstance = null;
    // 给谁发送消息

    boolean isFriend = true;
    boolean isAllLover = false;// 是否双方都是恋爱体验师
    boolean isAllLoverTestOrderSponsor = false;// 在双方都是恋爱体验师的试聊单里是发起者
    boolean isAllLoverOrderSponsor = true;// 在双方都是恋爱体验师的单里是发起者
    boolean callEnalbe = false;// 是否可以打电话
    boolean isOrderGoing = false;// 订单是否正在进行中
    boolean messageEnable = false;// 是否可以发消息
    boolean isNetWorkEnable = false;// 网络是否加载好
    boolean isSponsNewTestOrder = false;// 若自己是申请者的是否新的试聊
    boolean isWinnerNewTestOrder = false;// 若自己是被申请者的是否是新的试聊
    boolean isSponsNewOrder = false;// 若自己是申请者是否是新的单
    boolean isWinnerNewOrder = false;// 若自己是被申请者的是否是新的单
    boolean hasTestOrderChance = false; // 是否有试聊的机会
    boolean hasTestOrderChanceWithHer = false; // 是否和次人有试聊的机会
    boolean isLoverToNoraml = false; // 是否恋爱体验师与普通人聊天
    boolean isSponsTimeout = false;// 申请者超时
    boolean isWinnerTimeout = false;// 被申请者超时
    boolean isTestOrderAddTen = false;// 测试单被加了十分钟
    boolean isOrderAddTen = false;// 正式的单被加了十分钟
    boolean isTestOrderGoing = false;// 试聊正在进行中
    String curOrderId = null;
    MLOrder curOrder = null;
    String curTestOrerId = null;
    MLTestOrder curTestOrder = null;

    private String toChatUsername;
    public static String toChatUserAvatar;
    public static String toChatUserNick;
    private VoiceRecorder voiceRecorder;
    private MessageAdapter adapter;
    private File cameraFile;
    static int resendPos;
    // 谁发的消息
    private String fromChatUsername;
    private String fromChatUserAvatar;
    private String fromChatUserNick;
    private MLUser currentUser;
    private MLUser toUser;
    private JSONObject fromuser;
    private JSONObject touser;
    MLReportRecord mlReportRecord;

    private LinearLayout rl_bottom;
    private LinearLayout call_content;
    private LinearLayout bar_bottom;
    private LinearLayout lin_forbidden;

    private ImageView iv_emoticons_normal;
    private ImageView iv_emoticons_checked;
    private RelativeLayout edittext_layout;
    private RelativeLayout rlTimeCutDown;
    private ProgressBar loadmorePB;
    private boolean isloading;
    private final int pagesize = 20;
    private boolean haveMoreData = true;
    public String playMsgId;
    private MLUser toChatUser;

    private AudioManager audioManager;// 监听听筒模式
    private SensorManager mSensorManager;
    private Sensor mSensor;
    private EMChatOptions chatOptions;
    private boolean isHeadSet = false;
    private BroadcastReceiver headsetPlugReceiver = new BroadcastReceiver() {// 监听耳机状态
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.hasExtra("state")) {
                if (intent.getIntExtra("state", 0) == 0) {// 不插耳机
                    isHeadSet = false;
                    chatOptions.setUseSpeaker(true);
                    audioManager.setMode(AudioManager.MODE_NORMAL);
                    audioManager.setSpeakerphoneOn(true);
                    // Toast.makeText(context, "headset not connected",
                    // Toast.LENGTH_LONG).show();
                } else if (intent.getIntExtra("state", 0) == 1) {// 插耳机
                    isHeadSet = true;
                    chatOptions.setUseSpeaker(false);
                    audioManager.setMode(AudioManager.MODE_IN_CALL);
                    setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
                    audioManager.setSpeakerphoneOn(false);// 关闭扬声器
                    audioManager
                            .setRouting(AudioManager.MODE_NORMAL,
                                    AudioManager.ROUTE_EARPIECE,
                                    AudioManager.ROUTE_ALL);
                    // Toast.makeText(context, "headset  connected",
                    // Toast.LENGTH_LONG).show();
                }
            }
            // Log.e("==voice", "voice:" + chatOptions.getUseSpeaker());
        }
    };

    // 购买dailog
    private WheelTimeContinued wheelTimeContinued;
    private int selectedIndex = 2;// 当前选择时光,默认3小时

    private int[] costTimes = {30, 60, 180, 1440, 10080, 43200};
    private String[] costDate = {"半小时", "1小时", "3小时", "1天", "7天", "30天"};
    private static final String[] PLANETS = new String[]{"半小时（30时光）",
            "1小时（50时光）", "3小时（120时光）", "1天（200时光）", "7天（1200时光）", "30天（4500时光）"};
    private int[] costGold = {30, 50, 120, 200, 1200, 4500};

    private static final String[] PLANETS_EDIT = new String[]{"半小时（50时光）",
            "1小时（70时光）", "3小时（150时光）", "1天（300时光）", "7天（1800时光）", "30天（6500时光）"};
    private int[] costGold_edit = {50, 70, 150, 300, 1800, 6500};

    // 倒计时相关
    public long testOrderTime = 1200000;// ms 20分钟
    public LinearLayout linGetLover;
    public LinearLayout lineLoverAdd;
    public TextView btnGetLover;
    public TextView btnLoverAdd;
    private CountDownTimerView countdownTimerChat;
    private boolean isTimerRuning = false;
    private double charge;

    private Handler micImageHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            // 切换msg切换图片
            micImage.setImageDrawable(micImages[msg.what]);
        }
    };
    private EMGroup group;

    private LinearLayout llMore;// 更多那一层
    private ImageView ivTime;// 时间icon
    private ImageView ivMore;
    private ImageView ivFriendMore;
    private TitlePopup titlePopup;
    private TitlePopup titlePopupFriend;
    private LinearLayout top_tip;

    public int stat;// 是否通过了申请
    private LoadingDailog loading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        // 异步检测对方状态，以保障准确性。
        checkToUserType();
        initListener();
        initView();
        initHeader();

        setUpView();
    }

    private void initListener() {
        audioManager = (AudioManager) this
                .getSystemService(Context.AUDIO_SERVICE);
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
        chatOptions = EMChatManager.getInstance().getChatOptions();
        registerHeadsetPlugReceiver();
    }

    private void registerHeadsetPlugReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.HEADSET_PLUG");
        registerReceiver(headsetPlugReceiver, filter);
    }

    private void checkToUserType() {
        toChatUsername = getIntent().getStringExtra("userId");
        touser = MLCache.getCache().getAsJSONObject(toChatUsername);
        if (touser == null) {
            AVQuery<MLUser> query = new AVQuery<MLUser>(
                    "_User");
            query.getInBackground(
                    toChatUsername,
                    new GetCallback<MLUser>() {

                        @Override
                        public void done(
                                MLUser newuser,
                                AVException e) {
                            if (e == null) {
                                MLCache.saveStranger(newuser);
                                touser = MLCache.getCache().getAsJSONObject(toChatUsername);
                            }
                        }
                    });
        } else {
            AVQuery<MLUser> query = new AVQuery<MLUser>("_User");
            query.getInBackground(toChatUsername, new GetCallback<MLUser>() {

                @Override
                public void done(MLUser user, AVException e) {
                    if (e == null) {
                        try {
                            if (user.getType() != touser.getInt("type")) {
                                MLCache.getCache().put(toChatUsername,
                                        user.toJSONObject());
                                ToolKits.toast(ChatActivity.this, "对方身份已改变，请重试！");
                                ChatActivity.this.finish();
                            }
                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            });
        }


    }

    private void initHeader() {

        toChatUsername = getIntent().getStringExtra("userId");
        toChatUserAvatar = getIntent().getStringExtra("avatar");
        toChatUserNick = getIntent().getStringExtra("nickName");
        currentUser = UserService.getCurrentUser();
        fromChatUsername = currentUser.getObjectId();
        fromChatUserAvatar = currentUser.getAvatarUrl();
        fromChatUserNick = currentUser.getNickname();
        rlTimeCutDown = (RelativeLayout) findViewById(R.id.rlTimeCutDown);
        countdownTimerChat = (CountDownTimerView) findViewById(R.id.countdownTimerChat);
        linGetLover = (LinearLayout) findViewById(R.id.linGetLover);
        linGift = (LinearLayout) findViewById(R.id.linGift);

        isFriend = MLCache.isFriend(toChatUsername);

        // 倒计时
        linGetLover = (LinearLayout) findViewById(R.id.linGetLover);
        lineLoverAdd = (LinearLayout) findViewById(R.id.lineLoverAdd);
        btnGetLover = (TextView) findViewById(R.id.btnGetLover);
        btnLoverAdd = (TextView) findViewById(R.id.btnLoverAdd);

        // 判断是否是好友是否显示加好友
        llMore = (LinearLayout) findViewById(R.id.llMore);
        ivTime = (ImageView) findViewById(R.id.ivTime);
        ivMore = (ImageView) findViewById(R.id.ivMore);
        ivFriendMore = (ImageView) findViewById(R.id.ivFriendMore);

        // 是好友的操作
        // 实例化标题栏弹窗
        titlePopup = new TitlePopup(this, LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        // 给标题栏弹窗添加子类
        titlePopup.addAction(new ActionItem(this, "加为恋人"));
        titlePopup.addAction(new ActionItem(this, "拉黑"));
        titlePopup.setItemOnClickListener(new OnItemOnClickListener() {

            @Override
            public void onItemClick(ActionItem item, int position) {
                switch (position) {
                    case 0:
                        LayoutInflater inflater = LayoutInflater
                                .from(ChatActivity.this);
                        final View applyView = inflater.inflate(
                                R.layout.view_apply, null);
                        final EditText etReason = (EditText) applyView
                                .findViewById(R.id.etReason);
                        final MyAlertDialog dialog = new MyAlertDialog(
                                ChatActivity.this).builder()
                                .setTitle("申请成为对方的虚拟恋人").setView(applyView)
                                .setNegativeButton("取消", new OnClickListener() {
                                    @Override
                                    public void onClick(View v) {

                                    }
                                });
                        dialog.setPositiveButton("确定", new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                final String reason = etReason.getText().toString();
                                AVQuery<MLUser> query = new AVQuery<MLUser>("_User");
                                query.getInBackground(toChatUsername,
                                        new GetCallback<MLUser>() {

                                            @Override
                                            public void done(MLUser user,
                                                             AVException e) {
                                                if (e == null) {
                                                    AVAnalytics.onEvent(
                                                            ChatActivity.this,
                                                            "加为虚拟恋人");
                                                    MLUser usertemp = new MLUser();
                                                    usertemp.setObjectId(user
                                                            .getObjectId());
                                                    MolianContactManager
                                                            .getInstance()
                                                            .addContact(
                                                                    usertemp,
                                                                    etReason.getText()
                                                                            .toString());
                                                } else {
                                                    ToolKits.toast(
                                                            ChatActivity.this,
                                                            "发送失败，请检查网络");
                                                }
                                            }
                                        });
                            }
                        });
                        dialog.show();
                        break;
                    case 1:
                        final MyAlertDialog dialog2 = new MyAlertDialog(
                                ChatActivity.this).builder().setTitle("提示")
                                .setMsg("您是否要将" + toChatUserNick + "加入黑名单？")
                                .setNegativeButton("取消", new OnClickListener() {
                                    @Override
                                    public void onClick(View v) {

                                    }
                                });
                        dialog2.setPositiveButton("确定", new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                addUserToBlacklist(toChatUsername);
                                AVAnalytics.onEvent(ChatActivity.this, "拉黑");
                            }
                        });
                        dialog2.show();
                        break;
                    default:
                        break;
                }

            }
        });
        ivMore.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                titlePopup.show(v);
            }
        });

        titlePopupFriend = new TitlePopup(this, LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        // 给标题栏弹窗添加子类
        titlePopupFriend.addAction(new ActionItem(this, "拉黑"));
        titlePopupFriend.addAction(new ActionItem(this, "我要分手"));
        titlePopupFriend.setItemOnClickListener(new OnItemOnClickListener() {

            @Override
            public void onItemClick(ActionItem item, int position) {
                switch (position) {
                    case 0:// 拉黑
                        final MyAlertDialog dialog2 = new MyAlertDialog(
                                ChatActivity.this).builder().setTitle("提示")
                                .setMsg("您是否要将" + toChatUserNick + "加入黑名单？")
                                .setNegativeButton("取消", new OnClickListener() {
                                    @Override
                                    public void onClick(View v) {

                                    }
                                });
                        dialog2.setPositiveButton("确定", new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                addUserToBlacklist(toChatUsername);
                                AVAnalytics.onEvent(ChatActivity.this, "拉黑");
                            }
                        });
                        dialog2.show();
                        break;
                    case 1: // 分手
                        breakup();
                        break;
                }

            }
        });
        ivFriendMore.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                titlePopupFriend.show(v);
            }
        });
        rlTimeCutDown.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                hideKeyboard();
                if (rlTimeCutDown.getVisibility() == View.VISIBLE) {
                    rlTimeCutDown.setVisibility(View.GONE);
                }
            }
        });
        ivTime.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (rlTimeCutDown.getVisibility() == View.VISIBLE) {
                    rlTimeCutDown.setVisibility(View.GONE);
                } else {
                    hideKeyboard();
                    rlTimeCutDown.setVisibility(View.VISIBLE);
                    if (isTimerRuning == false) {
                        // initTimer(countdownTime);
                        // countdownTimerChat.start();
                        isTimerRuning = true;
                    }
                    // countdownTimerChat
                    // .setOnTimeCompleteListener(new OnTimeCompleteListener() {
                    //
                    // @Override
                    // public void onTimeComplete() {
                    // // TODO Auto-generated method stub
                    //
                    // }
                    // });
                }
            }
        });

        // 加载时间模块，这里很复杂 包括生成定时器

        try {
            checkTimeStatus();
        } catch (JSONException e1) {
            e1.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        rl_bottom = (LinearLayout) findViewById(R.id.rl_bottom);
        call_content = (LinearLayout) findViewById(R.id.call_content);
        // 头部tip
        top_tip = (LinearLayout) findViewById(R.id.top_tip);
        if (isFriend) {
            top_tip.setVisibility(View.GONE);
            bar_bottom.setVisibility(View.VISIBLE);

        } else {
            if (getIntent().getStringExtra("userId").equals(Constant.SYSTEM)) {
                toChatUserNick = "口袋君";
                linGift.setVisibility(View.GONE);
                AVAnalytics.onEvent(ChatActivity.this, "口袋君");
                TextView btn_call = (TextView) findViewById(R.id.btn_call);
                btn_call.setVisibility(View.GONE);
                messageEnable = true;
                isNetWorkEnable = true;
            }
            // initBottom();
        }
        if (!getIntent().getStringExtra("userId").equals(Constant.SYSTEM)
                && UserService.getCurrentUser().getStatus() == C.USER_STATUS_FORBIDDEN) {
            SimpleDateFormat sDateFormat = new SimpleDateFormat(
                    "yyyy-MM-dd hh:mm:ss");
            String curDate = sDateFormat.format(new java.util.Date());
            String date = MLContext.getForbiddenTime("forbidden");
            try {
                Date d1 = sDateFormat.parse(curDate);
                Date d2 = sDateFormat.parse(date);
                long diff = (d1.getTime() - d2.getTime()) / 1000;// 这样得到秒级别
                if (diff >= 86400) {// 一天后解封
                    MLContext.saveForbiddenTime("forbidden", "");
                    UserService.getCurrentUser()
                            .setStatus(C.USER_STATUS_NORMAL);
                    UserService.getCurrentUser().saveInBackground();
                    lin_forbidden.setVisibility(View.GONE);
                    bar_bottom.setVisibility(View.VISIBLE);
                } else {
                    bar_bottom.setVisibility(View.INVISIBLE);
                    lin_forbidden.setVisibility(View.VISIBLE);
                    call_content.setVisibility(View.GONE);
                }

            } catch (Exception e) {
            }

        } else {
            lin_forbidden.setVisibility(View.GONE);
        }
    }

    public void checkTimeStatus() throws Exception {
        fromuser = MLCache.getCache().getAsJSONObject(fromChatUsername);
        touser = MLCache.getCache().getAsJSONObject(toChatUsername);
        final boolean ishasTestOrderTo = MLCache.isHasTestOrder(toChatUsername);

        // Log.e("from", fromuser.getInt("type") + "");
        // Log.e("from", touser.getInt("type") + "");

        // 两者都是普通人
        if (fromuser.getInt("type") == C.USER_TYPE_NORMAL
                && touser.getInt("type") == C.USER_TYPE_NORMAL) {
            if (isFriend) {
                messageEnable = true;
                isNetWorkEnable = true;
                callEnalbe = true;
                ivFriendMore.setVisibility(View.VISIBLE);
                ivMore.setVisibility(View.GONE);
                ivTime.setVisibility(View.GONE);
            } else {
                messageEnable = true;
                isNetWorkEnable = true;
                callEnalbe = false;
                ivFriendMore.setVisibility(View.GONE);
                ivMore.setVisibility(View.VISIBLE);
                ivTime.setVisibility(View.GONE);
            }
        }
        // 如果自己是普通人，对方是恋爱体验师
        if (fromuser.getInt("type") == C.USER_TYPE_NORMAL
                && touser.getInt("type") != C.USER_TYPE_NORMAL) {

            // 倒计时5分钟的事件
            initFiveMinRestHandler(fromuser.getInt("type"),
                    touser.getInt("type"));
            ivTime.setVisibility(View.VISIBLE);
            try {
                initTimerBuy(touser.getInt("type"));
            } catch (JSONException e1) {
                e1.printStackTrace();
            }

            if (isFriend) {
                // 不用判断是否有试聊直接，直接判断是否有正式的单,正式的单里面结束的单还要判断是否有恋爱加时的时间，fuck
                hasTestOrderChanceWithHer = false;
                normalToLoverFriend();// 自己是普通人，对方是恋爱体验师，且双方是好友
            } else {
                // Log.e("非好友", "非好友");
                hasTestOrderChanceWithHer = true;
                // 查找今天是否有试聊机会
                checkIfHasChatChangeToday(ishasTestOrderTo);
            }
        }

        // 如果自己是恋爱体验师，对方是普通人
        if (fromuser.getInt("type") != C.USER_TYPE_NORMAL
                && touser.getInt("type") == C.USER_TYPE_NORMAL) {
            // 倒计时5分钟的事件
            initFiveMinRestHandler(fromuser.getInt("type"),
                    touser.getInt("type"));
            ivTime.setVisibility(View.VISIBLE);
            // 将试聊设为可试聊
            hasTestOrderChance = true;
            hasTestOrderChanceWithHer = true;
            initLoverTen();
            if (isFriend) {
                // 证明已经聊过天查看是否有正在进行的单
                hasTestOrderChanceWithHer = false;
                LoverToNormalFriend();// 自己是恋爱体验师，对方是普通人，且双方是好友
            } else {
                // 非好友查询有没有试聊
                // 去查找试聊
                LoverToNormalFindTestOrder();// 自己是恋爱体验师，对方是普通人，去查找试聊单
            }
        }

        // 双方都是恋爱体验师的恶心情况，真tmd恶心
        if (fromuser.getInt("type") != C.USER_TYPE_NORMAL
                && touser.getInt("type") != C.USER_TYPE_NORMAL) {
            // 倒计时5分钟的事件
            initFiveMinRestHandler(fromuser.getInt("type"),
                    touser.getInt("type"));
            ivTime.setVisibility(View.VISIBLE);
            isAllLover = true;
            if (isFriend) {// 双方是好友
                // Log.e("==", "all is lover and they r friend");
                // 证明已经聊过天查看是否有正在进行的单
                hasTestOrderChanceWithHer = false;
                MLUser toUser = new MLUser();
                toUser.setObjectId(toChatUsername);

                AVQuery<MLOrder> orderquery1 = new AVQuery<MLOrder>("MLOrder");
                orderquery1.whereEqualTo("sponsor", toUser);
                orderquery1
                        .whereEqualTo("winner", UserService.getCurrentUser());
                orderquery1.whereLessThan("status", 4);

                AVQuery<MLOrder> orderquery2 = new AVQuery<MLOrder>("MLOrder");
                orderquery2.whereEqualTo("sponsor",
                        UserService.getCurrentUser());
                orderquery2.whereEqualTo("winner", toUser);
                orderquery2.whereLessThan("status", 4);

                List<AVQuery<MLOrder>> queries = new ArrayList<AVQuery<MLOrder>>();
                queries.add(orderquery1);
                queries.add(orderquery2);

                AVQuery<MLOrder> mainQuery = AVQuery.or(queries);
                mainQuery.orderByDescending("createdAt");
                mainQuery.findInBackground(new FindCallback<MLOrder>() {

                    @Override
                    public void done(List<MLOrder> Orders, AVException e) {
                        isNetWorkEnable = true;
                        if (e == null) {
                            // Log.e("size", Orders.size() + "");
                            if (Orders.size() != 0) {
                                MLOrder order = Orders.get(0);
                                curOrder = order;
                                curOrderId = order.getObjectId();

                                // 判断自己是否是发起者
                                if (order.getSponsor().getObjectId()
                                        .equals(fromChatUsername)) {// 如果自己是发起者，则相当于普通人对恋爱体验师的方式
                                    try {
                                        initTimerBuy(touser.getInt("type"));
                                    } catch (JSONException e1) {
                                        e1.printStackTrace();
                                    }
                                    // Log.e("==", "我发起的聊天");
                                    isAllLoverOrderSponsor = true;
                                    Integer status = order.getStatus();
                                    if (status == C.ORDER_SATAUS_WAITING) {
                                        check30MinOut(order);
                                        // // 初始化计时器
                                        initTimer(
                                                ((long) curOrder.getPeriod()) * 60 * 1000,
                                                false);
                                    } else if (status == C.ORDER_SATAUS_GOING) {
                                        initTimerLeft(Orders.get(0));
                                    } else {
                                        // 订单已经结束，判断是否有加时的时间
                                        initLoverTimerLeft(Orders.get(0));
                                    }
                                    // normalToLoverFriend();//
                                    // 自己是普通人，对方是恋爱体验师，且双方是好友
                                } else { // 如果自己不是发起者，则相当于恋爱体验师对普通人的方式
                                    initLoverTen();
                                    // Log.e("==", "我接单");
                                    isAllLoverOrderSponsor = false;
                                    LoverToNormalFriend();// 自己是恋爱体验师，对方是普通人，且双方是好友
                                }

                            } else {
                                // Log.e("==", "还没有发起聊天过");
                                try {
                                    initTimerBuy(touser.getInt("type"));
                                } catch (JSONException e1) {
                                    e1.printStackTrace();
                                }
                                // normalToLoverFriend();//
                                // 自己是普通人，对方是恋爱体验师，且双方是好友
                            }
                        } else {
                            // Log.e("err", e.getMessage());
                        }
                    }
                });
            } else {
                // Log.e("==", "all is lover and they r not fri");

                // 不是好友
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("userId", fromChatUsername);
                AVCloud.callFunctionInBackground("isHasTestOrder", params,
                        new FunctionCallback<String>() {// 查找有无试聊机会

                            @Override
                            public void done(String result, AVException e) {
                                isNetWorkEnable = true;
                                if (e == null) {
                                    if (result.equals("true")) {// 今日无试聊机会
                                        // Log.e("==", "今日没有试聊机会");
                                        hasTestOrderChance = false;
                                        // 如果有试聊则查询
                                        if (ishasTestOrderTo) {// 有试聊
                                            // Log.e("=====", "曾经有试聊,自己发起的");
                                            try {
                                                initTimerBuy(touser
                                                        .getInt("type"));
                                            } catch (JSONException e1) {
                                                e1.printStackTrace();
                                            }
                                            toFindTestOrder();
                                        } else {// 本地没有记录自己发起试聊
                                            // 去查找对方有没有和本人有试聊
                                            LoverToLoverFindTestOrder();
                                        }
                                    } else {// 今日有试聊机会
                                        // Log.e("==", "今日有试聊机会");
                                        hasTestOrderChance = true;
                                        // 去查找对方有没有和本人有试聊
                                        LoverToLoverFindTestOrder();
                                    }
                                } else {
                                    ToolKits.toast(ChatActivity.this,
                                            "加载失败请检查网络");
                                }
                            }
                        });
            }
        }
    }

    private void LoverToNormalFindTestOrder() {// 自己是恋爱体验师，对方是普通人，去查找试聊单
        // TODO Auto-generated method stub
        MLUser toUser = new MLUser();
        toUser.setObjectId(toChatUsername);
        AVQuery<MLTestOrder> orderquery = new AVQuery<MLTestOrder>(
                "MLTestOrder");
        orderquery.whereEqualTo("sponsor", toUser);
        orderquery.orderByDescending("createdAt");
        orderquery.whereEqualTo("winner", UserService.getCurrentUser());
        orderquery.findInBackground(new FindCallback<MLTestOrder>() {

            @Override
            public void done(List<MLTestOrder> testOrders, AVException e) {
                isNetWorkEnable = true;
                if (e == null) {
                    // Log.e("size", testOrders.size() + "");
                    if (testOrders.size() != 0) {
                        MLTestOrder testOrder = testOrders.get(0);
                        curTestOrder = testOrder;
                        curTestOrerId = testOrder.getObjectId();
                        isTestOrderGoing = true;
                        // 如果发现有试聊单，如果是未结束
                        if (testOrder.getStatus() == C.ORDER_STATUS_WAITING) {
                            // Log.e("试聊等待中", "s");
                            messageEnable = true;
                            callEnalbe = false;
                            isWinnerNewTestOrder = true;
                            hasTestOrderChanceWithHer = true;
                            curTestOrerId = testOrder.getObjectId();
                            curTestOrder = testOrder;
                            initTestTimerLeft(testOrder);
                        } else if (testOrder.getStatus() == C.ORDER_SATAUS_GOING) {
                            // Log.e("试聊进行中中", "s");
                            // 需要初始化倒计时
                            initTestTimerLeft(testOrder);
                        } else if (testOrder.getStatus() == C.ORDER_STATUS_COMMENT) {
                            // Log.e("试聊已结束", "s");
                            // // 试聊已经结束不能发消息
                            // messageEnable = false;
                            // callEnalbe = false;
                            // hasTestOrderChanceWithHer = false;
                            initLoverTestTimerLeft(testOrder);
                            // 初始化充值页面
                        } else if (testOrder.getStatus() == C.ORDER_STATUS_FINISH) {
                            initLoverTestTimerLeft(testOrder);
                        } else {
                            // 试聊已经结束不能发消息
                            messageEnable = false;
                            callEnalbe = false;
                        }

                    } else {// 没有试聊
                        hasTestOrderChanceWithHer = true;
                        isLoverToNoraml = true;
                    }
                } else {
                    ToolKits.toast(ChatActivity.this, "加载失败请检查网络");
                }
            }
        });
    }

    private void LoverToLoverFindTestOrder() {// 自己是恋爱体验师，对方是恋爱体验师，去查找对方是否有试聊单
        // TODO Auto-generated method stub
        MLUser toUser = new MLUser();
        toUser.setObjectId(toChatUsername);
        AVQuery<MLTestOrder> orderquery = new AVQuery<MLTestOrder>(
                "MLTestOrder");
        orderquery.whereEqualTo("sponsor", toUser);
        orderquery.orderByDescending("createdAt");
        orderquery.whereEqualTo("winner", UserService.getCurrentUser());
        orderquery.findInBackground(new FindCallback<MLTestOrder>() {

            @Override
            public void done(List<MLTestOrder> testOrders, AVException e) {
                isNetWorkEnable = true;
                if (e == null) {
                    if (testOrders.size() != 0) {// 对方和本人试聊过，不可以再试聊了
                        initLoverTen();
                        isAllLoverTestOrderSponsor = true;
                        // Log.e("==", "对方是恋爱体验师，对方发起的聊天,不可以再试聊了");
                        hasTestOrderChanceWithHer = false;
                        MLTestOrder testOrder = testOrders.get(0);
                        curTestOrder = testOrder;
                        curTestOrerId = testOrder.getObjectId();
                        // 如果发现有试聊单，如果是未结束
                        if (testOrder.getStatus() == C.ORDER_STATUS_WAITING) {
                            // Log.e("试聊等待中", "s");
                            isTestOrderGoing = true;
                            messageEnable = true;
                            callEnalbe = false;
                            isWinnerNewTestOrder = true;
                            hasTestOrderChanceWithHer = true;
                            curTestOrerId = testOrder.getObjectId();
                            curTestOrder = testOrder;
                            initTestTimerLeft(testOrder);
                        } else if (testOrder.getStatus() == C.ORDER_SATAUS_GOING) {
                            // Log.e("试聊进行中中", "s");
                            // 需要初始化倒计时
                            isTestOrderGoing = true;
                            initTestTimerLeft(testOrder);
                        } else if (testOrder.getStatus() == C.ORDER_STATUS_COMMENT) {
                            // Log.e("试聊已结束", "s");
                            // // 试聊已经结束不能发消息
                            // messageEnable = false;
                            // callEnalbe = false;
                            // hasTestOrderChanceWithHer = false;
                            initLoverTestTimerLeft(testOrder);
                            // 初始化充值页面
                        } else if (testOrder.getStatus() == C.ORDER_STATUS_FINISH) {
                            initLoverTestTimerLeft(testOrder);
                        } else {
                            // 试聊已经结束不能发消息
                            messageEnable = false;
                            callEnalbe = false;
                        }
                    } else {// 对方和本人没有试聊过，可以试聊
                        try {
                            initTimerBuy(touser.getInt("type"));
                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                        hasTestOrderChanceWithHer = true;
                        if (hasTestOrderChance) {
                            // Log.e("==", "对方是恋爱体验师，对方和本人没有试聊过，可以试聊");
                            isSponsNewTestOrder = true;
                            messageEnable = true;
                        } else {
                            // Log.e("==", "对方是恋爱体验师，对方和本人没有试聊过，但今天没有试聊机会");
                            messageEnable = false;
                        }
                        callEnalbe = false;
                    }
                } else {
                    ToolKits.toast(ChatActivity.this, "加载失败请检查网络");
                }
            }
        });
    }

    private void LoverToNormalFriend() {// 自己是恋爱体验师,对方是普通人，且双方是好友
        // TODO Auto-generated method stub
        MLUser toUser = new MLUser();
        toUser.setObjectId(toChatUsername);

        AVQuery<MLOrder> orderquery = new AVQuery<MLOrder>("MLOrder");
        orderquery.whereEqualTo("sponsor", toUser);
        orderquery.whereEqualTo("winner", UserService.getCurrentUser());
        orderquery.orderByDescending("createdAt");
        orderquery.whereLessThan("status", 4);
        orderquery.findInBackground(new FindCallback<MLOrder>() {

            @Override
            public void done(List<MLOrder> Orders, AVException e) {
                isNetWorkEnable = true;
                if (e == null) {
                    // Log.e("size", Orders.size() + "");
                    if (Orders.size() != 0) {
                        MLOrder order = Orders.get(0);
                        curOrder = order;
                        curOrderId = order.getObjectId();
                        isTestOrderGoing = false;
                        Integer status = order.getStatus();
                        if (status == C.ORDER_SATAUS_WAITING) {
                            callEnalbe = false;
                            isOrderGoing = false;
                            check30MinOut(order);
                            initTimer(
                                    ((long) curOrder.getPeriod()) * 60 * 1000,
                                    false);

                        } else if (status == C.ORDER_SATAUS_GOING) {
                            initTimerLeft(Orders.get(0));
                            isOrderGoing = true;
                            callEnalbe = true;
                        } else {// 判断是否有爱心加时
                            initLoverTimerLeft(curOrder);
                        }

                    }
                } else {
                    // Log.e("err", e.getMessage());
                }
            }
        });
    }

    private void checkIfHasChatChangeToday(final boolean ishasTestOrderTo) { // 双方不是好友，查找今天是否有试聊机会

        // TODO Auto-generated method stub
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", fromChatUsername);
        AVCloud.callFunctionInBackground("isHasTestOrder", params,
                new FunctionCallback<String>() {

                    @Override
                    public void done(String result, AVException e) {
                        if (e == null) {
                            // Log.e("result", result);
                            if (result.equals("true")) {
                                hasTestOrderChance = false;
                                // 如果有试聊则查询，如果无试聊则准备开始试聊
                                if (ishasTestOrderTo) {
                                    // Log.e("=====", "曾经有试聊");
                                    toFindTestOrder(); // 去查找试聊
                                } else {
                                    isNetWorkEnable = true;
                                }
                            } else {
                                hasTestOrderChance = true;
                                hasTestOrderChanceWithHer = true;

                                // 如果有试聊则查询，如果无试聊则准备开始试聊
                                if (ishasTestOrderTo) {
                                    // Log.e("=====", "曾经有试聊");
                                    toFindTestOrder();// 去查找试聊
                                } else {
                                    // Log.e("试聊", "可试聊");
                                    // 可以准备试聊啦
                                    messageEnable = true;
                                    isSponsNewTestOrder = true;
                                    hasTestOrderChanceWithHer = true;
                                    isNetWorkEnable = true;
                                }

                            }
                        }
                    }
                });
    }

    protected void toFindTestOrder() { // 自己是普通人，去查找和此人是否有试聊
        // TODO Auto-generated method stub
        MLUser toUser = new MLUser();
        toUser.setObjectId(toChatUsername);
        AVQuery<MLTestOrder> orderquery = new AVQuery<MLTestOrder>(
                "MLTestOrder");
        orderquery.whereEqualTo("sponsor", UserService.getCurrentUser());
        orderquery.whereEqualTo("winner", toUser);
        orderquery.orderByDescending("createdAt");
        orderquery.findInBackground(new FindCallback<MLTestOrder>() {

            @Override
            public void done(List<MLTestOrder> testOrders, AVException e) {
                isNetWorkEnable = true;
                if (e == null) {
                    if (testOrders.size() != 0) {
                        hasTestOrderChanceWithHer = false;
                        MLTestOrder testOrder = testOrders.get(0);
                        curTestOrder = testOrder;
                        curTestOrerId = testOrder.getObjectId();
                        if (isAllLover) {// 如果双方都是恋爱体验师
                            isAllLoverTestOrderSponsor = true;
                        }
                        // 如果发现有试聊单，如果是未结束.结束的还要判断是否有加时
                        if (testOrder.getStatus() == C.ORDER_SATAUS_WAITING
                                || testOrder.getStatus() == C.ORDER_SATAUS_GOING) {
                            // 需要初始化倒计时
                            initTestTimerLeft(testOrder);
                            isTestOrderGoing = true;
                        } else if (testOrder.getStatus() == C.ORDER_STATUS_FINISH
                                || testOrder.getStatus() == C.ORDER_STATUS_COMMENT) {
                            initLoverTestTimerLeft(testOrder);
                        } else {
                            // 试聊已经结束不能发消息
                            messageEnable = false;
                            callEnalbe = false;
                        }
                    } else {
                        hasTestOrderChanceWithHer = true;
                    }
                } else {
                    ToolKits.toast(ChatActivity.this, "加载失败请检查网络");
                }
            }
        });
    }

    private void normalToLoverFriend() {// 自己是普通人，对方是恋爱体验师，且双方是好友
        // TODO Auto-generated method stub
        MLUser toUser = new MLUser();
        toUser.setObjectId(toChatUsername);
        AVQuery<MLOrder> orderquery = new AVQuery<MLOrder>("MLOrder");
        orderquery.whereEqualTo("sponsor", UserService.getCurrentUser());
        orderquery.whereEqualTo("winner", toUser);
        orderquery.orderByDescending("createdAt");
        orderquery.whereLessThan("status", 4);

        orderquery.findInBackground(new FindCallback<MLOrder>() {

            @Override
            public void done(List<MLOrder> Orders, AVException e) {
                isNetWorkEnable = true;
                if (e == null) {
                    // Log.e("size", Orders.size() + "");
                    if (Orders.size() != 0) {
                        MLOrder order = Orders.get(0);
                        curOrder = order;
                        curOrderId = order.getObjectId();
                        isTestOrderGoing = false;

                        Integer status = order.getStatus();
                        if (status == C.ORDER_SATAUS_WAITING) {
                            check30MinOut(order);
                            // // 初始化计时器
                            initTimer(
                                    ((long) curOrder.getPeriod()) * 60 * 1000,
                                    false);
                        } else if (status == C.ORDER_SATAUS_GOING) {
                            initTimerLeft(Orders.get(0));
                        } else {
                            // 订单已经结束，判断是否有加时的时间
                            initLoverTimerLeft(Orders.get(0));
                        }
                    } else {// 以前没有订单
                        // Log.e("==", "还没有订单");
                        try {
                            initTimerBuy(touser.getInt("type"));
                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            }
        });
    }

    // 检测正式单是否超过三十分钟，超过了则设置状态
    private void check30MinOut(final MLOrder order) {
        AVCloud.callFunctionInBackground("getNetTime", null,
                new FunctionCallback<Long>() {

                    @Override
                    public void done(Long time, AVException e) {
                        if (e == null) {

                            Long startTime = order.getCreatedAt().getTime();
                            Long nowTime = time;
                            Long outTime = nowTime - startTime;
                            if (outTime >= 1800000) {// 大于30分钟
                                messageEnable = false;
                                order.setStatus(C.ORDER_STATUS_CANCLE);
                                order.saveInBackground();
                            } else {
                                messageEnable = true;
                                try {
                                    if (fromuser.getInt("type") != C.USER_TYPE_NORMAL) {
                                        isWinnerNewOrder = true;
                                        // callEnalbe = true;
                                    }
                                } catch (JSONException e1) {
                                    e1.printStackTrace();
                                }

                            }
                        }
                    }

                });
    }

    // 初始化正式时间
    private void initTimerLeft(final MLOrder order) {
        // 获取网络时间
        AVCloud.callFunctionInBackground("getNetTime", null,
                new FunctionCallback<Long>() {

                    @Override
                    public void done(Long time, AVException e) {
                        if (e == null) {

                            Long leftTime;
                            boolean isReply;
                            if (order.getStartTime() != null) {
                                // Log.e("err", "getStartTime is not nullllllll");

                                Long endTime = order.getStartTime().getTime()
                                        + ((long) order.getPeriod()) * 60 * 1000;// 开始时间+购买分钟
                                Long nowTime = time;
                                leftTime = endTime - nowTime;
                                isReply = true;// 判断此订单是否正在进行中
                            } else {
                                // Log.e("err", "getStartTime is  nullllllll");

                                leftTime = ((long) order.getPeriod()) * 60 * 1000;
                                isReply = false;
                            }
                            // Log.e("leftTime", leftTime + "");
                            if (leftTime > 0) {
                                messageEnable = true;
                                callEnalbe = true;
                                // 初始化计时器
                                initTimer(leftTime, isReply);

                            } else {
                                // 订单时间已经到了，但是状态不对
                                messageEnable = false;
                                callEnalbe = false;
                                order.setStatus(C.ORDER_STATUS_COMMENT);
                                order.saveInBackground();
                            }

                        }
                    }

                });
    }

    // 初始化有恋爱加时的时间
    private void initLoverTimerLeft(final MLOrder order) {
        if (order.getLoveStartTime() == null) {
            messageEnable = false;
            callEnalbe = false;

        } else {
            // 获取网络时间
            AVCloud.callFunctionInBackground("getNetTime", null,
                    new FunctionCallback<Long>() {

                        @Override
                        public void done(Long time, AVException e) {
                            if (e == null) {

                                Long endTime = order.getLoveStartTime().getTime() + 10 * 60 * 1000;// 开始时间+加时的10分钟
                                Long nowTime = time;
                                Long leftTime = endTime - nowTime;
                                if (leftTime > 0) {
                                    messageEnable = true;
                                    callEnalbe = true;
                                    // 初始化计时器
                                    initTimer(leftTime, true);
                                }
                            }
                        }
                    });
        }

    }

    // 初始化测试订单的时间
    private void initTestTimerLeft(final MLTestOrder testorder) {
        // 获取网络时间
        AVCloud.callFunctionInBackground("getNetTime", null,
                new FunctionCallback<Long>() {

                    @Override
                    public void done(Long time, AVException e) {
                        if (e == null) {

                            Long restTime;
                            boolean isReply;
                            if (testorder.getStartTime() != null) {
                                // Log.e("err", "getStartTime is not nullllllll");

                                Long endTime = testorder.getStartTime().getTime() + 20 * 60 * 1000;// 开始时间+20分钟

                                Long nowTime = time;
                                restTime = endTime - nowTime;
                                isReply = true;// 判断此订单是否正在进行中
                            } else {
                                // Log.e("err", "getStartTime is  nullllllll");
                                restTime = (long) (20 * 60 * 1000);// 开始时间+20分钟
                                isReply = false;
                            }
                            if (restTime > 0) {
                                isTestOrderGoing = true;
                                messageEnable = true;
                                hasTestOrderChanceWithHer = true;
                                // 初始化计时器
                                initTimer(restTime, isReply);

                            } else {
                                // 订单时间已经到了，但是状态不对
                                messageEnable = false;
                                hasTestOrderChanceWithHer = false;
                                testorder.setStatus(C.ORDER_STATUS_FINISH);
                                testorder.saveInBackground();
                                try {
                                    initTimerBuy(touser.getInt("type"));
                                } catch (JSONException e1) {
                                    e1.printStackTrace();
                                }
                            }
                        }
                    }

                });
    }

    // 初始化有加时的测试订单的时间
    private void initLoverTestTimerLeft(final MLTestOrder testorder) {
        if (testorder.getLoveStartTime() == null) {
            messageEnable = false;
            callEnalbe = false;
            hasTestOrderChanceWithHer = false;

        } else {
            // 获取网络时间
            AVCloud.callFunctionInBackground("getNetTime", null,
                    new FunctionCallback<Long>() {

                        @Override
                        public void done(Long time, AVException e) {
                            if (e == null) {

                                Long endTime = testorder.getLoveStartTime()
                                        .getTime() + 10 * 60 * 1000;// 开始时间+10分钟
                                Long nowTime = time;
                                Long restTime = endTime - nowTime;
                                if (restTime > 0) {
                                    messageEnable = true;
                                    hasTestOrderChanceWithHer = true;
                                    isTestOrderGoing = true;
                                    callEnalbe = false;
                                    // 初始化计时器
                                    initTimer(restTime, true);

                                }
                            }
                        }

                    });

        }
    }

    /*
     * isStart:true或false ，决定定时器是否运行
	 */
    public void initTimer(Long time, boolean isStart) {
        countdownTimerChat.stopCountDown();
        countdownTimerChat.setTime(time);
        if (isStart) {
            countdownTimerChat.startCountDown();
            isOrderGoing = true;
        }
    }

    public void freshOrderAndiniTimer(boolean freshOrderAndiniTimer) {
        adapter.refreshSelectLast();
        MLUser toUser = new MLUser();
        toUser.setObjectId(toChatUsername);

        AVQuery<MLOrder> orderquery = new AVQuery<MLOrder>("MLOrder");
        if (freshOrderAndiniTimer) {
            orderquery.whereEqualTo("sponsor", toUser);
            orderquery.whereEqualTo("winner", UserService.getCurrentUser());
        } else {
            orderquery.whereEqualTo("sponsor", UserService.getCurrentUser());
            orderquery.whereEqualTo("winner", toUser);
        }
        orderquery.whereLessThan("status", 2);
        orderquery.findInBackground(new FindCallback<MLOrder>() {

            @Override
            public void done(List<MLOrder> Orders, AVException e) {
                isNetWorkEnable = true;
                if (e == null) {
                    // Log.e("size", "Orders:" + Orders.size() + "");
                    if (Orders.size() != 0) {
                        isTestOrderGoing = false;

                        final MLOrder order = Orders.get(0);
                        String orderId = null;
                        orderId = order.getObjectId();
                        if (curOrderId != null && curOrder.getStatus() < 2) {
                            curOrder = order;
                            curOrderId = orderId;
                            isOrderGoing = true;
                            if (curOrder.getStatus() == 0) {
                                isOrderGoing = false;
                            }
                            refreshInitTime(curOrder);
                        } else {
                            curOrder = order;
                            curOrderId = orderId;
                            if (UserService.getCurrentUser().getType() != C.USER_TYPE_NORMAL) {
                                isWinnerNewOrder = true;
                                isOrderGoing = false;
                                isWinnerNewTestOrder = false;
                            }
                            refreshInitTime(curOrder);
                        }

                    }
                } else {
                    // Log.e("err", e.getMessage());
                }
            }
        });

    }

    public void refreshInitTime(final MLOrder order) {
        isTestOrderGoing = false;

        // 获取网络时间
        AVCloud.callFunctionInBackground("getNetTime", null,
                new FunctionCallback<Long>() {

                    @Override
                    public void done(Long time, AVException e) {
                        if (e == null) {

                            Long leftTime;
                            boolean isReply;
                            if (order.getStartTime() != null) {
                                Long endTime = order.getStartTime().getTime()
                                        + ((long) order.getPeriod()) * 60 * 1000;// 开始时间+购买分钟
                                Long nowTime = time;
                                leftTime = endTime - nowTime;
                                isReply = true;// 判断此订单是否正在进行中
                            } else {

                                leftTime = ((long) order.getPeriod()) * 60 * 1000;
                                isReply = false;
                            }
                            if (leftTime > 0) {
                                messageEnable = true;
                                callEnalbe = true;
                                if (isReply) {
                                    isOrderGoing = true;
                                } else {
                                    isOrderGoing = false;
                                }
                                // 初始化计时器
                                initTimer(leftTime, isReply);

                            } else {
                                // 订单时间已经到了，但是状态不对
                                messageEnable = false;
                                isOrderGoing = false;
                                callEnalbe = false;
                                order.setStatus(C.ORDER_STATUS_COMMENT);
                                order.saveInBackground();
                            }

                        }
                    }

                });
    }

    public void freshTimer(String orderId) {
        AVQuery<MLOrder> query = new AVQuery<MLOrder>("MLOrder");
        query.getInBackground(orderId, new GetCallback<MLOrder>() {

            @Override
            public void done(final MLOrder order, AVException e) {
                if (e == null) {
                    // 获取网络时间
                    AVCloud.callFunctionInBackground("getNetTime", null,
                            new FunctionCallback<Long>() {

                                @Override
                                public void done(Long time, AVException e) {
                                    if (e == null) {

                                        Long leftTime;
                                        if (order.getStartTime() != null) {
                                            Long endTime = order.getStartTime()
                                                    .getTime()
                                                    + ((long) order.getPeriod())
                                                    * 60 * 1000;// 开始时间+购买分钟
                                            Long nowTime = time;
                                            leftTime = endTime - nowTime;
                                        } else {
                                            leftTime = ((long) order.getPeriod()) * 60 * 1000;
                                        }
                                        if (leftTime > 0) {
                                            isTestOrderGoing = false;

                                            messageEnable = true;
                                            callEnalbe = true;
                                            // 初始化计时器
                                            initTimer(leftTime, true);

                                        } else {
                                            // 订单时间已经到了，但是状态不对
                                            messageEnable = false;
                                            callEnalbe = false;
                                            order.setStatus(C.ORDER_STATUS_COMMENT);
                                            order.saveInBackground();
                                        }
                                    }
                                }

                            });

                }
            }
        });
    }

    // 有爱心加时，且在当前页面的的时候需要刷新
    public void freshLoverTenAddedTimer() {
        // 保存一条被加时的消息到本地
        adapter.refreshSelectLast();
        if (curTestOrerId != null && curOrderId == null) {
            // 给当前的测试单加时间并计时
            AVQuery<MLTestOrder> query = new AVQuery<MLTestOrder>("MLTestOrder");
            query.getInBackground(curTestOrerId,
                    new GetCallback<MLTestOrder>() {

                        @Override
                        public void done(final MLTestOrder order, AVException e) {
                            if (e == null) {
                                // 获取网络时间
                                AVCloud.callFunctionInBackground("getNetTime",
                                        null, new FunctionCallback<Long>() {

                                            @Override
                                            public void done(Long time,
                                                             AVException e) {
                                                if (e == null) {

                                                    Long endTime = order
                                                            .getLoveStartTime()
                                                            .getTime() + 10 * 60 * 1000;// 开始时间+购买分钟
                                                    Long nowTime = time;
                                                    Long leftTime = endTime
                                                            - nowTime;
                                                    if (leftTime > 0) {
                                                        messageEnable = true;
                                                        callEnalbe = true;
                                                        // 初始化计时器
                                                        initTimer(leftTime, true);

                                                    } else {
                                                        // 爱心时间已超过
                                                        messageEnable = false;
                                                        callEnalbe = false;
                                                        ToolKits.toast(
                                                                ChatActivity.this,
                                                                "恋爱加时已经超时");
                                                    }

                                                }
                                            }
                                        });

                            }
                        }
                    });

        }
        // 如果是正式单
        if (curOrderId != null) {
            // 给当前的测试单加时间并计时
            AVQuery<MLOrder> query = new AVQuery<MLOrder>("MLOrder");
            query.getInBackground(curOrderId, new GetCallback<MLOrder>() {

                @Override
                public void done(final MLOrder order, AVException e) {
                    if (e == null) {
                        // 获取网络时间
                        AVCloud.callFunctionInBackground("getNetTime", null,
                                new FunctionCallback<Long>() {

                                    @Override
                                    public void done(Long time, AVException e) {
                                        if (e == null) {

                                            Long endTime = order.getLoveStartTime()
                                                    .getTime() + 10 * 60 * 1000;// 开始时间+购买分钟
                                            Long nowTime = time;
                                            Long leftTime = endTime - nowTime;
                                            if (leftTime > 0) {
                                                isTestOrderGoing = false;

                                                messageEnable = true;
                                                callEnalbe = true;
                                                // 初始化计时器
                                                initTimer(leftTime, true);

                                            } else {
                                                // 爱心时间已超过
                                                messageEnable = false;
                                                callEnalbe = false;
                                                ToolKits.toast(ChatActivity.this,
                                                        "恋爱加时已经超时");
                                            }

                                        }
                                    }
                                });

                    }
                }
            });

        }

    }

    private void initTimerBuy(int type) {
        linGetLover.setVisibility(View.VISIBLE);
        lineLoverAdd.setVisibility(View.GONE);
        if (type == C.USER_TYPE_LOVER) {
            linGetLover.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    alertBuyDailog(PLANETS, costGold, "");
                    AVAnalytics.onEvent(ChatActivity.this, "点击领走虚拟恋人");
                }
            });

        } else if (type == C.USER_TYPE_RECOMMENDED) {
            // 编辑推荐的购买方案
            linGetLover.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    alertBuyDailog(PLANETS_EDIT, costGold_edit, "");

                }
            });

        }
    }

    public void alertBuyDailog(String[] plants, final int[] costs, String title) {
        // 普通恋爱体验师的购买方案
        if (StringUtils.isEmpty(title)) {
            title = "领走虚拟恋人";
        }
        LayoutInflater inflater = LayoutInflater.from(ChatActivity.this);
        View timepickerview = inflater.inflate(R.layout.wheeltime_continue,
                null);
        wheelTimeContinued = (WheelTimeContinued) timepickerview
                .findViewById(R.id.wheeltime);
        wheelTimeContinued.setOffset(2);
        wheelTimeContinued.setItems(Arrays.asList(plants));
        wheelTimeContinued.setSeletion(2);
        wheelTimeContinued
                .setOnWheelViewListener(new WheelTimeContinued.OnWheelViewListener() {
                    @Override
                    public void onSelected(int selected, String item) {
                        selectedIndex = selected - 2;
                    }
                });
        final MyAlertDialog dialog = new MyAlertDialog(ChatActivity.this)
                .builder().setTitle(title).setView(timepickerview)
                .setNegativeButton("取消", new OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
        dialog.setPositiveButton("领走", new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectedIndex >= costTimes.length) {// 可能造成数组溢出
                    return;
                }
                final int costTime = costTimes[selectedIndex];
                final int costGold = costs[selectedIndex];
                final String time = costDate[selectedIndex];
                // 现判断有没有钱
                if (UserService.getCurrentUser().getBalance() * 10 - costGold < 0) {
                    final MyAlertDialog dialogCache = new MyAlertDialog(
                            ChatActivity.this).builder().setTitle("提示")
                            .setMsg("您的时光不够了")
                            .setNegativeButton("取消", new OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                }
                            });
                    dialogCache.setPositiveButton("去充值", new OnClickListener() {
                        @SuppressLint("SimpleDateFormat")
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(ChatActivity.this,
                                    Wallet.class);
                            intent.putExtra("balance", currentUser.getBalance());
                            startActivity(intent);
                            AVAnalytics.onEvent(ChatActivity.this, "我的钱包充值");
                        }
                    });
                    dialogCache.show();
                    return;
                }
                // 首先要扣钱
                UserService.getCurrentUser().increment("balance",
                        -(costGold / 10));
                UserService.getCurrentUser().saveInBackground(
                        new SaveCallback() {

                            @Override
                            public void done(AVException e) {
                                if (e == null) {
                                    isTestOrderGoing = false;
                                    isSponsNewOrder = true;
                                    if (curOrderId == null
                                            || (curOrderId != null && curOrder
                                            .getStatus() >= 2)) {
                                        // 如果没有正式的单，那么创建正式的单。若有测试的单则将测试的单改为已完成，并完成相互加好友。。。。这么复杂
                                        final MLOrder newOrder = new MLOrder();
                                        final MLUser sponsor = new MLUser();
                                        MLUser winner = new MLUser();
                                        sponsor.setObjectId(fromChatUsername);
                                        winner.setObjectId(toChatUsername);
                                        newOrder.setSponsor(sponsor);
                                        newOrder.setWinner(winner);
                                        newOrder.setStatus(C.ORDER_SATAUS_WAITING);
                                        newOrder.setCost(costGold);
                                        newOrder.setPeriod(costTime);
                                        newOrder.saveInBackground(new SaveCallback() {

                                            @Override
                                            public void done(AVException e) {
                                                if (e == null) {
                                                    // 控件倒计时初始化并停止，等待对方回应,
                                                    countdownTimerChat
                                                            .stopCountDown();
                                                    countdownTimerChat
                                                            .setTime(((long) costTime) * 60 * 1000);
                                                    callEnalbe = false;
                                                    messageEnable = true;
                                                    curOrderId = newOrder
                                                            .getObjectId();
                                                    curOrder = newOrder;
                                                    // 如果有试聊单则修改状态
                                                    if (curTestOrerId != null) {
                                                        MLTestOrder testOrder = new MLTestOrder();
                                                        testOrder
                                                                .setObjectId(curTestOrerId);
                                                        testOrder
                                                                .setStatus(C.ORDER_STATUS_FINISH);
                                                        testOrder
                                                                .saveInBackground();
                                                    }
                                                    // 判断是否是好友，如果不是则加对方为好友
                                                    if (!isFriend) {
                                                        // 把对方添加到自己的试聊
                                                        // MLCache.saveTestOrderUserId(toChatUsername);
                                                        Map<String, Object> params = new HashMap<String, Object>();
                                                        params.put("touserId",
                                                                toChatUsername);
                                                        params.put(
                                                                "fromuserId",
                                                                fromChatUsername);
                                                        params.put("nick",
                                                                fromChatUsername);
                                                        params.put(
                                                                "actions",
                                                                C.ACTION_FRIEND_APPLY_ACCEPTED);
                                                        AVCloud.callFunctionInBackground(
                                                                "sendFriendApplyMsg",
                                                                params,
                                                                new FunctionCallback<Object>() {

                                                                    @Override
                                                                    public void done(
                                                                            Object arg0,
                                                                            AVException e) {
                                                                        if (e == null) {
                                                                            // 添加好友

                                                                            UserService
                                                                                    .getCurrentUser()
                                                                                    .followInBackground(
                                                                                            toChatUsername,
                                                                                            new FollowCallback<AVObject>() {

                                                                                                @Override
                                                                                                public void done(
                                                                                                        AVObject arg0,
                                                                                                        AVException e) {
                                                                                                    if (e != null) {
                                                                                                    }

                                                                                                }
                                                                                            });
                                                                            // 保存好友
                                                                            MLCache.saveFriendId(toChatUsername);
                                                                            // 保存一条本地提示
                                                                            MolianContactManager
                                                                                    .getInstance()
                                                                                    .saveNewGrayMsg(
                                                                                            toChatUsername,
                                                                                            toChatUserNick,
                                                                                            C.GRAY_MEG_NORMAL_TIMEADD,
                                                                                            null);
                                                                            adapter.refreshSelectLast();

                                                                            // 通知恋爱体验师
                                                                            MolianContactManager
                                                                                    .getInstance()
                                                                                    .sendCMDMsg_ADDTime(
                                                                                            fromChatUserNick,
                                                                                            toChatUsername,
                                                                                            C.ACTION_ORDER_NORMAL_ADDTIME,
                                                                                            time,
                                                                                            null);
                                                                            MolianContactManager
                                                                                    .getInstance()
                                                                                    .sendSysMsg(
                                                                                            toChatUsername,
                                                                                            fromChatUserNick
                                                                                                    + "对你续时"
                                                                                                    + time
                                                                                                    + "，你们将作为虚拟恋人互相陪伴，快去跟Ta聊聊吧。");
                                                                            // 是否要发短息
                                                                            checkOnlineAndSendSns(
                                                                                    toChatUsername,
                                                                                    1);

                                                                        }
                                                                    }
                                                                });
                                                    } else {
                                                        // 保存一条本地提示
                                                        MolianContactManager
                                                                .getInstance()
                                                                .saveNewGrayMsg(
                                                                        toChatUsername,
                                                                        toChatUserNick,
                                                                        C.GRAY_MEG_NORMAL_TIMEADD,
                                                                        null);
                                                        adapter.refreshSelectLast();

                                                        // 通知恋爱体验师
                                                        MolianContactManager
                                                                .getInstance()
                                                                .sendCMDMsg_ADDTime(
                                                                        fromChatUserNick,
                                                                        toChatUsername,
                                                                        C.ACTION_ORDER_NORMAL_ADDTIME,
                                                                        time,
                                                                        null);
                                                        MolianContactManager
                                                                .getInstance()
                                                                .sendSysMsg(
                                                                        toChatUsername,
                                                                        fromChatUserNick
                                                                                + "对你续时"
                                                                                + time
                                                                                + "，你们将作为虚拟恋人互相陪伴，快去跟Ta聊聊吧。");

                                                        // 是否要发短息
                                                        checkOnlineAndSendSns(
                                                                toChatUsername,
                                                                1);

                                                    }

                                                } else {
                                                    // Log.e("err",
                                                    // e.getMessage());
                                                    ToolKits.toast(
                                                            ChatActivity.this,
                                                            "购买超时，请检查网络");
                                                }
                                            }
                                        });

                                    } else if (curOrderId != null
                                            && curOrder.getStatus() < 2) {
                                        // 如果有正式的单，则在单上加时
                                        AVQuery<MLOrder> order = new AVQuery<MLOrder>(
                                                "MLOrder");
                                        order.getInBackground(curOrderId,
                                                new GetCallback<MLOrder>() {

                                                    @Override
                                                    public void done(
                                                            final MLOrder order,
                                                            AVException e) {
                                                        if (e == null) {
                                                            curOrder = order;
                                                            order.increment(
                                                                    "cost",
                                                                    costGold);
                                                            order.increment(
                                                                    "period",
                                                                    costTime);
                                                            order.saveInBackground(new SaveCallback() {

                                                                @Override
                                                                public void done(
                                                                        AVException e) {
                                                                    if (e == null) {
                                                                        // 通知恋爱体验师
                                                                        MolianContactManager
                                                                                .getInstance()
                                                                                .sendCMDMsg_ADDTime(
                                                                                        fromChatUserNick,
                                                                                        toChatUsername,
                                                                                        C.ACTION_ORDER_NORMAL_ADDTIME,
                                                                                        time,
                                                                                        null);
                                                                        MolianContactManager
                                                                                .getInstance()
                                                                                .sendSysMsg(
                                                                                        toChatUsername,
                                                                                        fromChatUserNick
                                                                                                + "对你续时"
                                                                                                + time
                                                                                                + "，你们将作为虚拟恋人互相陪伴，快去跟Ta聊聊吧。");
                                                                        // 是否要发短息
                                                                        checkOnlineAndSendSns(
                                                                                toChatUsername,
                                                                                1);

                                                                        initTimerLeft(order);
                                                                    }
                                                                }
                                                            });
                                                        }
                                                    }
                                                });

                                    }
                                } else {
                                    ToolKits.toast(ChatActivity.this,
                                            "续时失败，请检查网络");
                                }
                            }
                        });

            }
        });
        dialog.show();

    }

    private void initLoverTen() {
        linGetLover.setVisibility(View.GONE);
        lineLoverAdd.setVisibility(View.VISIBLE);
        lineLoverAdd.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // 爱心加时
                // Log.e("爱心加时", "加时");

                if (curTestOrerId != null && curOrderId == null) {
                    // Log.e("爱心加时", "测试单加时");
                    AVQuery<MLTestOrder> query = new AVQuery<MLTestOrder>(
                            "MLTestOrder");
                    query.getInBackground(curTestOrerId,
                            new GetCallback<MLTestOrder>() {

                                @Override
                                public void done(final MLTestOrder testorder,
                                                 AVException e) {
                                    if (e == null) {
                                        if (testorder.getLoveStartTime() != null) {
                                            // lineLoverAdd.setBackgroundResource(R.drawable.shape_btn_sure_grey);
                                            ToolKits.toast(ChatActivity.this,
                                                    "您已使用过爱心加时的机会啦！");
                                        } else if (testorder.getStatus() < 2) {
                                            // lineLoverAdd.setBackgroundResource(R.drawable.shape_btn_sure_grey);
                                            ToolKits.toast(ChatActivity.this,
                                                    "你们的聊天时间还没有到，不用太急！");
                                        } else {
                                            // 获取网络时间
                                            AVCloud.callFunctionInBackground(
                                                    "getNetTime",
                                                    null,
                                                    new FunctionCallback<Long>() {

                                                        @Override
                                                        public void done(
                                                                Long time,
                                                                AVException e) {
                                                            if (e == null) {

                                                                Date date = new Date(
                                                                        time);

                                                                testorder
                                                                        .setLoveStartTime(date);
                                                                testorder
                                                                        .saveInBackground(new SaveCallback() {

                                                                            @Override
                                                                            public void done(
                                                                                    AVException e) {
                                                                                if (e == null) {
                                                                                    initTimer(
                                                                                            (long) (10 * 60 * 1000),
                                                                                            true);
                                                                                    messageEnable = true;
                                                                                    callEnalbe = true;
                                                                                    // 保存一条本地的信息并发透传给对方
                                                                                    // 保存一条本地提示
                                                                                    MolianContactManager
                                                                                            .getInstance()
                                                                                            .saveNewGrayMsg(
                                                                                                    toChatUsername,
                                                                                                    toChatUserNick,
                                                                                                    C.GRAY_MEG_LOVER_ADD,
                                                                                                    null);
                                                                                    adapter.refreshSelectLast();

                                                                                    // 通知普通人
                                                                                    MolianContactManager
                                                                                            .getInstance()
                                                                                            .sendCMDMsg(
                                                                                                    fromChatUserNick,
                                                                                                    toChatUsername,
                                                                                                    C.ACTION_ORDER_LOVER_ADDTIME,
                                                                                                    null);
                                                                                    MolianContactManager
                                                                                            .getInstance()
                                                                                            .sendSysMsg(
                                                                                                    toChatUsername,
                                                                                                    fromChatUserNick
                                                                                                            + "给了你爱心加时，聊天时间多了10分钟，看来Ta很喜欢你哦～");
                                                                                }

                                                                            }
                                                                        });
                                                            }
                                                        }
                                                    });

                                        }
                                    }
                                }
                            });

                } else if (curOrderId != null) {
                    // 如果有正式单
                    isTestOrderGoing = false;

                    AVQuery<MLOrder> query = new AVQuery<MLOrder>("MLOrder");
                    query.getInBackground(curOrderId,
                            new GetCallback<MLOrder>() {

                                @Override
                                public void done(final MLOrder order,
                                                 AVException e) {
                                    if (e == null) {
                                        if (order.getLoveStartTime() != null) {
                                            // lineLoverAdd.setBackgroundResource(R.drawable.shape_btn_sure_grey);
                                            ToolKits.toast(ChatActivity.this,
                                                    "您已使用过爱心加时的机会啦！");
                                        } else if (order.getStatus() < 2) {
                                            // lineLoverAdd.setBackgroundResource(R.drawable.shape_btn_sure_grey);
                                            ToolKits.toast(ChatActivity.this,
                                                    "你们的聊天时间还没有到，不用太急！");
                                        } else {
                                            // 获取网络时间
                                            AVCloud.callFunctionInBackground(
                                                    "getNetTime",
                                                    null,
                                                    new FunctionCallback<Long>() {

                                                        @Override
                                                        public void done(
                                                                Long time,
                                                                AVException e) {
                                                            if (e == null) {

                                                                Date date = new Date(
                                                                        time);

                                                                order.setLoveStartTime(date);
                                                                order.saveInBackground(new SaveCallback() {

                                                                    @Override
                                                                    public void done(
                                                                            AVException e) {
                                                                        if (e == null) {
                                                                            initTimer(
                                                                                    (long) (10 * 60 * 1000),
                                                                                    true);
                                                                            messageEnable = true;
                                                                            callEnalbe = true;
                                                                            // 保存一条本地的信息并发透传给对方
                                                                            // 保存一条本地提示
                                                                            MolianContactManager
                                                                                    .getInstance()
                                                                                    .saveNewGrayMsg(
                                                                                            toChatUsername,
                                                                                            toChatUserNick,
                                                                                            C.GRAY_MEG_LOVER_ADD,
                                                                                            null);
                                                                            adapter.refreshSelectLast();

                                                                            // 通知普通人
                                                                            MolianContactManager
                                                                                    .getInstance()
                                                                                    .sendCMDMsg(
                                                                                            fromChatUserNick,
                                                                                            toChatUsername,
                                                                                            C.ACTION_ORDER_LOVER_ADDTIME,
                                                                                            null);
                                                                            MolianContactManager
                                                                                    .getInstance()
                                                                                    .sendSysMsg(
                                                                                            toChatUsername,
                                                                                            fromChatUserNick
                                                                                                    + "给了你爱心加时，聊天时间多了10分钟，看来Ta很喜欢你哦～");
                                                                        }

                                                                    }
                                                                });
                                                            }
                                                        }
                                                    });

                                        }
                                    }
                                }
                            });
                } else if (curTestOrerId == null && curOrderId == null) {
                    // lineLoverAdd.setBackgroundResource(R.drawable.shape_btn_sure_grey);
                    ToolKits.toast(ChatActivity.this, "加时失败，要等对方领走你哦");
                }

            }
        });
    }

    // 5分钟剩余倒计时的事件
    private void initFiveMinRestHandler(final int fromUserType,
                                        final int touserType) {
        countdownTimerChat.setOnTimerListener(new TimerListener() {

            @Override
            public void onTick(long millisUntilFinished) {
                // 当小于5分钟的一瞬间的事件
                if (millisUntilFinished <= 300000
                        && millisUntilFinished > 299000) {
                    // 保存一条本地提示
                    if (touserType == C.USER_TYPE_NORMAL
                            || (isAllLoverTestOrderSponsor && touserType != C.USER_TYPE_NORMAL)) {
                        MolianContactManager.getInstance().saveNewGrayMsg(
                                toChatUsername, toChatUserNick,
                                C.GRAY_MEG_NORMAL_REST_FIVE, null);
                        adapter.refreshSelectLast();

                    } else {
                        MolianContactManager.getInstance().saveNewGrayMsg(
                                toChatUsername, toChatUserNick,
                                C.GRAY_MEG_LOVER_REST_FIVE, null);
                        adapter.refreshSelectLast();
                    }

                }
            }

            @Override
            public void onFinish() {
                callEnalbe = false;
                messageEnable = false;
                // 当结束时如果有测试单，修改测试单的状态，正式单修改正式单的状态

                if (curOrderId != null) {
                    MLOrder order = new MLOrder();
                    order.setObjectId(curOrderId);
                    order.setStatus(C.ORDER_STATUS_COMMENT);
                    order.saveInBackground();
                    // // 保存一条本地提示
                    // if (fromUserType == C.USER_TYPE_NORMAL
                    // || (isAllLoverOrderSponsor && touserType !=
                    // C.USER_TYPE_NORMAL)) {
                    // MolianContactManager.getInstance().saveNewGrayMsg(
                    // toChatUsername, toChatUserNick,
                    // C.GRAY_MEG_NORMAL_TIMEOUT, null);
                    // adapter.refreshSelectLast();
                    //
                    // }
                    // // 保存一条本地提示
                    // else if (fromUserType != C.USER_TYPE_NORMAL) {
                    // MolianContactManager.getInstance().saveNewGrayMsg(
                    // toChatUsername, toChatUserNick,
                    // C.GRAY_MEG_LOVER_TIMEOUT, null);
                    // adapter.refreshSelectLast();
                    //
                    // }

                }
                if (curTestOrerId != null && curOrderId == null) {
                    MLTestOrder testorder = new MLTestOrder();
                    testorder.setObjectId(curTestOrerId);
                    testorder.setStatus(C.ORDER_STATUS_FINISH);
                    testorder.saveInBackground();
                    // // 保存一条本地提示
                    // if (fromUserType == C.USER_TYPE_NORMAL
                    // || (isAllLoverOrderSponsor && touserType !=
                    // C.USER_TYPE_NORMAL)) {
                    // MolianContactManager.getInstance().saveNewGrayMsg(
                    // toChatUsername, toChatUserNick,
                    // C.GRAY_MEG_NORMAL_TIMEOUT_TEST, null);
                    // adapter.refreshSelectLast();
                    //
                    // }
                    // // 保存一条本地提示
                    // else if (fromUserType != C.USER_TYPE_NORMAL) {
                    // MolianContactManager.getInstance().saveNewGrayMsg(
                    // toChatUsername, toChatUserNick,
                    // C.GRAY_MEG_LOVER_TIMEOUT, null);
                    // adapter.refreshSelectLast();
                    //
                    // }

                }
            }
        });
    }

    public void freshMsg() {
        adapter.refreshSelectLast();
    }

    /**
     * initView
     */
    protected void initView() {
        recordingContainer = findViewById(R.id.recording_container);
        micImage = (ImageView) findViewById(R.id.mic_image);
        Chat_btn = (ImageView) findViewById(R.id.Chat_btn);
        recordingHint = (TextView) findViewById(R.id.recording_hint);
        listView = (ListView) findViewById(R.id.list);
        mEditTextContent = (PasteEditText) findViewById(R.id.et_sendmessage);
        buttonSetModeKeyboard = findViewById(R.id.btn_set_mode_keyboard);
        edittext_layout = (RelativeLayout) findViewById(R.id.edittext_layout);
        buttonSetModeVoice = findViewById(R.id.btn_set_mode_voice);
        buttonSend = findViewById(R.id.btn_send);
        buttonPressToSpeak = findViewById(R.id.btn_press_to_speak);
        expressionViewpager = (ViewPager) findViewById(R.id.vPager);
        emojiIconContainer = (LinearLayout) findViewById(R.id.ll_face_container);
        iv_emoticons_normal = (ImageView) findViewById(R.id.iv_emoticons_normal);
        iv_emoticons_checked = (ImageView) findViewById(R.id.iv_emoticons_checked);
        btnContainer = (LinearLayout) findViewById(R.id.ll_btn_container);
        callContent = (LinearLayout) findViewById(R.id.Call_btn);
        bar_bottom = (LinearLayout) findViewById(R.id.bar_bottom);
        lin_forbidden = (LinearLayout) findViewById(R.id.lin_forbidden);
        btn_box = (Button) findViewById(R.id.btn_box);
        // iv_emoticons_normal = (ImageView)
        // findViewById(R.id.iv_emoticons_normal);
        // iv_emoticons_checked = (ImageView)
        // findViewById(R.id.iv_emoticons_checked);
        loadmorePB = (ProgressBar) findViewById(R.id.pb_load_more);
        // bar_bottom.setVisibility(View.INVISIBLE);
        // buttonSetModeVoice.setClickable(false);
        // btn_box.setClickable(false);
        iv_emoticons_normal.setVisibility(View.VISIBLE);
        iv_emoticons_checked.setVisibility(View.INVISIBLE);
        more = findViewById(R.id.more);
        edittext_layout.setBackgroundResource(R.drawable.input_bar_bg_normal);

        // 动画资源文件,用于录制语音时
        micImages = new Drawable[]{
                getResources().getDrawable(R.drawable.record_animate_01),
                getResources().getDrawable(R.drawable.record_animate_02),
                getResources().getDrawable(R.drawable.record_animate_03),
                getResources().getDrawable(R.drawable.record_animate_04),
                getResources().getDrawable(R.drawable.record_animate_05),
                getResources().getDrawable(R.drawable.record_animate_06),
                getResources().getDrawable(R.drawable.record_animate_07),
                getResources().getDrawable(R.drawable.record_animate_08),
                getResources().getDrawable(R.drawable.record_animate_09),
                getResources().getDrawable(R.drawable.record_animate_10),
                getResources().getDrawable(R.drawable.record_animate_11),
                getResources().getDrawable(R.drawable.record_animate_12),
                getResources().getDrawable(R.drawable.record_animate_13),
                getResources().getDrawable(R.drawable.record_animate_14),};

        // 表情list
        reslist = getExpressionRes(35);
        // 初始化表情viewpager
        List<View> views = new ArrayList<View>();
        View gv1 = getGridChildView(1);
        View gv2 = getGridChildView(2);
        views.add(gv1);
        views.add(gv2);
        expressionViewpager.setAdapter(new ExpressionPagerAdapter(views));
        edittext_layout.requestFocus();
        voiceRecorder = new VoiceRecorder(micImageHandler);
        buttonPressToSpeak.setOnTouchListener(new PressToSpeakListen());
        mEditTextContent.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    edittext_layout
                            .setBackgroundResource(R.drawable.input_bar_bg_active);
                } else {
                    edittext_layout
                            .setBackgroundResource(R.drawable.input_bar_bg_normal);
                }

            }
        });
        mEditTextContent.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                edittext_layout
                        .setBackgroundResource(R.drawable.input_bar_bg_active);
                more.setVisibility(View.GONE);
                iv_emoticons_normal.setVisibility(View.VISIBLE);
                iv_emoticons_checked.setVisibility(View.INVISIBLE);
                emojiIconContainer.setVisibility(View.GONE);
                btnContainer.setVisibility(View.GONE);
            }
        });
        // 监听文字框
        mEditTextContent.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (!TextUtils.isEmpty(s)) {
                    buttonSend.setVisibility(View.VISIBLE);
                } else {

                    buttonSend.setVisibility(View.GONE);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    private void setUpView() {
        activityInstance = this;
        iv_emoticons_normal.setOnClickListener(this);
        iv_emoticons_checked.setOnClickListener(this);
        // position = getIntent().getIntExtra("position", -1);
        clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
                .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");
        // 判断单聊还是群聊
        chatType = getIntent().getIntExtra("chatType", CHATTYPE_SINGLE);

        if (chatType == CHATTYPE_SINGLE) { // 单聊
            TextView title = ((TextView) findViewById(R.id.name));
            title.setText(toChatUserNick);
            // conversation =
            // EMChatManager.getInstance().getConversation(toChatUsername,false);
        } else {
            // 群聊
            findViewById(R.id.container_to_group).setVisibility(View.VISIBLE);
            // findViewById(R.id.container_remove).setVisibility(View.GONE);
            // findViewById(R.id.container_voice_call).setVisibility(View.GONE);
            // findViewById(R.id.container_video_call).setVisibility(View.GONE);
            toChatUsername = getIntent().getStringExtra("groupId");
            group = EMGroupManager.getInstance().getGroup(toChatUsername);
            if (group != null)
                ((TextView) findViewById(R.id.name)).setText(group
                        .getGroupName());
            else
                ((TextView) findViewById(R.id.name)).setText(toChatUserNick);
            // conversation =
            // EMChatManager.getInstance().getConversation(toChatUsername,true);
        }
        conversation = EMChatManager.getInstance().getConversation(
                toChatUsername);
        // 把此会话的未读数置为0
        conversation.resetUnreadMsgCount();

        // 初始化db时，每个conversation加载数目是getChatOptions().getNumberOfMessagesLoaded
        // 这个数目如果比用户期望进入会话界面时显示的个数不一样，就多加载一些
        final List<EMMessage> msgs = conversation.getAllMessages();
        int msgCount = msgs != null ? msgs.size() : 0;
        if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) {
            String msgId = null;
            if (msgs != null && msgs.size() > 0) {
                msgId = msgs.get(0).getMsgId();
            }
            if (chatType == CHATTYPE_SINGLE) {
                conversation.loadMoreMsgFromDB(msgId, pagesize);
            } else {
                conversation.loadMoreGroupMsgFromDB(msgId, pagesize);
            }
        }
        adapter = new MessageAdapter(this, toChatUsername, chatType);
        // 显示消息
        listView.setAdapter(adapter);
        listView.setOnScrollListener(new ListScrollListener());
        adapter.refreshSelectLast();

        listView.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideKeyboard();
                more.setVisibility(View.GONE);
                emojiIconContainer.setVisibility(View.GONE);
                btnContainer.setVisibility(View.GONE);
                return false;
            }
        });
        // 注册接收消息广播
        receiver = new NewMessageBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(EMChatManager
                .getInstance().getNewMessageBroadcastAction());
        // 设置广播的优先级别大于Mainacitivity,这样如果消息来的时候正好在chat页面，直接显示消息，而不是提示消息未读
        intentFilter.setPriority(5);
        registerReceiver(receiver, intentFilter);

        // 注册一个ack回执消息的BroadcastReceiver
        IntentFilter ackMessageIntentFilter = new IntentFilter(EMChatManager
                .getInstance().getAckMessageBroadcastAction());
        ackMessageIntentFilter.setPriority(5);
        registerReceiver(ackMessageReceiver, ackMessageIntentFilter);

        // 注册一个消息送达的BroadcastReceiver
        IntentFilter deliveryAckMessageIntentFilter = new IntentFilter(
                EMChatManager.getInstance()
                        .getDeliveryAckMessageBroadcastAction());
        deliveryAckMessageIntentFilter.setPriority(5);
        registerReceiver(deliveryAckMessageReceiver,
                deliveryAckMessageIntentFilter);

        // show forward message if the message is not null
        String forward_msg_id = getIntent().getStringExtra("forward_msg_id");
        if (forward_msg_id != null) {
            // 显示发送要转发的消息
            forwardMessage(forward_msg_id);
        }

    }

    /**
     * onActivityResult
     */
    @SuppressWarnings("deprecation")
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_CODE_EXIT_GROUP) {
            setResult(RESULT_OK);
            finish();
            return;
        }
        if (requestCode == REQUEST_CODE_CONTEXT_MENU) {
            switch (resultCode) {
                case RESULT_CODE_COPY: // 复制消息
                    EMMessage copyMsg = ((EMMessage) adapter.getItem(data
                            .getIntExtra("position", -1)));
                    // clipboard.setText(SmileUtils.getSmiledText(ChatActivity.this,
                    // ((TextMessageBody) copyMsg.getBody()).getMessage()));
                    clipboard.setText(((TextMessageBody) copyMsg.getBody())
                            .getMessage());
                    break;
                case RESULT_CODE_DELETE: // 删除消息
                    EMMessage deleteMsg = (EMMessage) adapter.getItem(data
                            .getIntExtra("position", -1));
                    conversation.removeMessage(deleteMsg.getMsgId());
                    adapter.refreshSeekTo(data.getIntExtra("position",
                            adapter.getCount()) - 1);
                    break;

                case RESULT_CODE_FORWARD: // 转发消息
                    // EMMessage forwardMsg = (EMMessage)
                    // adapter.getItem(data.getIntExtra("position", 0));
                    // Intent intent = new Intent(this,
                    // ForwardMessageActivity.class);
                    // intent.putExtra("forward_msg_id", forwardMsg.getMsgId());
                    // startActivity(intent);

                    break;

                default:
                    break;
            }
        }
        if (resultCode == RESULT_OK) { // 清空消息
            if (requestCode == REQUEST_CODE_SELECT_GIFT) {//收到礼物的反馈
//                sendGift(giftName, giftInfo, giftImg);
//                adapter.refreshSelectLast();
            } else if (requestCode == REQUEST_CODE_EMPTY_HISTORY) {
                // 清空会话
                EMChatManager.getInstance().clearConversation(toChatUsername);
                adapter.refresh();
            } else if (requestCode == REQUEST_CODE_CAMERA) { // 发送照片
                if (cameraFile != null && cameraFile.exists())
                    sendPicture(cameraFile.getAbsolutePath());
            } else if (requestCode == REQUEST_CODE_SELECT_VIDEO) { // 发送本地选择的视频

                int duration = data.getIntExtra("dur", 0);
                String videoPath = data.getStringExtra("path");
                File file = new File(PathUtil.getInstance().getImagePath(),
                        "thvideo" + System.currentTimeMillis());
                Bitmap bitmap = null;
                FileOutputStream fos = null;
                try {
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                    bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3);
                    if (bitmap == null) {
                        EMLog.d("chatactivity",
                                "problem load video thumbnail bitmap,use default icon");
                        bitmap = BitmapFactory.decodeResource(getResources(),
                                R.drawable.app_panel_video_icon);
                    }
                    fos = new FileOutputStream(file);

                    bitmap.compress(CompressFormat.JPEG, 100, fos);

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (fos != null) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        fos = null;
                    }
                    if (bitmap != null) {
                        bitmap.recycle();
                        bitmap = null;
                    }

                }
                sendVideo(videoPath, file.getAbsolutePath(), duration / 1000);

            } else if (requestCode == REQUEST_CODE_LOCAL) { // 发送本地图片
                if (data != null) {
                    Uri selectedImage = data.getData();
                    if (selectedImage != null) {
                        sendPicByUri(selectedImage);
                    }
                }
            } else if (requestCode == REQUEST_CODE_SELECT_FILE) { // 发送选择的文件
                if (data != null) {
                    Uri uri = data.getData();
                    if (uri != null) {
                        sendFile(uri);
                    }
                }

            } else if (requestCode == REQUEST_CODE_MAP) { // 地图
                double latitude = data.getDoubleExtra("latitude", 0);
                double longitude = data.getDoubleExtra("longitude", 0);
                String locationAddress = data.getStringExtra("address");
                if (locationAddress != null && !locationAddress.equals("")) {
                    more(more);
                    sendLocationMsg(latitude, longitude, "", locationAddress);
                } else {
                    String st = getResources().getString(
                            R.string.unable_to_get_loaction);
                    ToolKits.toast(this, st);
                }
                // 重发消息
            } else if (requestCode == REQUEST_CODE_TEXT
                    || requestCode == REQUEST_CODE_VOICE
                    || requestCode == REQUEST_CODE_PICTURE
                    || requestCode == REQUEST_CODE_LOCATION
                    || requestCode == REQUEST_CODE_VIDEO
                    || requestCode == REQUEST_CODE_FILE) {
                resendMessage();
            } else if (requestCode == REQUEST_CODE_COPY_AND_PASTE) {
                // 粘贴
                if (!TextUtils.isEmpty(clipboard.getText())) {
                    String pasteText = clipboard.getText().toString();
                    if (pasteText.startsWith(COPY_IMAGE)) {
                        // 把图片前缀去掉，还原成正常的path
                        sendPicture(pasteText.replace(COPY_IMAGE, ""));
                    }

                }
            } else if (conversation.getMsgCount() > 0) {
                adapter.refresh();
                setResult(RESULT_OK);
            } else if (requestCode == REQUEST_CODE_GROUP_DETAIL) {
                adapter.refresh();
            }
        }
    }

    /**
     * 消息图标点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        String st1 = getResources().getString(R.string.not_connect_to_server);
        int id = view.getId();
        if (id == R.id.btn_send) {// 点击发送按钮(发文字和表情)
            final String s = mEditTextContent.getText().toString();
            sendText(s);
        } else if (id == R.id.iv_emoticons_normal) { // 点击显示表情框
            more.setVisibility(View.VISIBLE);
            iv_emoticons_normal.setVisibility(View.INVISIBLE);
            iv_emoticons_checked.setVisibility(View.VISIBLE);
            btnContainer.setVisibility(View.GONE);
            emojiIconContainer.setVisibility(View.VISIBLE);
            hideKeyboard();
        } else if (id == R.id.iv_emoticons_checked) { // 点击隐藏表情框
            iv_emoticons_normal.setVisibility(View.VISIBLE);
            iv_emoticons_checked.setVisibility(View.INVISIBLE);
            btnContainer.setVisibility(View.VISIBLE);
            emojiIconContainer.setVisibility(View.GONE);
            more.setVisibility(View.GONE);

        } else if (id == R.id.btn_picture) {
            selectPicFromLocal(); // 点击图片图标
            // 点击图片图标
            // Intent intent = new Intent(ChatActivity.this,
            // ImageGridActivity.class);
            // startActivityForResult(intent, REQUEST_CODE_SELECT_VIDEO);
        } else if (id == R.id.btn_take_picture) { // 点击拍照图标
            selectPicFromCamera();// 点击照相图标
            // selectFileFromLocal();
        } else if (id == R.id.Call_btn) { // 点击打电话图标
            try {
                if (callEnalbe == false
                        && touser.getInt("type") == C.USER_TYPE_NORMAL) {
                    ToolKits.toast(ChatActivity.this, "暂无法通话，你们还不是好友");
                    return;
                } else if (callEnalbe == false
                        && touser.getInt("type") != C.USER_TYPE_NORMAL) {
                    ToolKits.toast(ChatActivity.this, "暂无法通话，对方是恋爱体验师");
                    return;
                }
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();

            }
            if (!EMChatManager.getInstance().isConnected()) {
                Toast.makeText(this, st1, 0).show();
            } else {
                AVQuery<MLUser> query = new AVQuery<MLUser>("_User");
                query.getInBackground(toChatUsername,
                        new GetCallback<MLUser>() {

                            @Override
                            public void done(MLUser user, AVException e) {
                                if (e == null) {
                                    toUser = user;
                                    if (user.getType() == C.USER_TYPE_NORMAL) {
                                        startActivity(new Intent(
                                                ChatActivity.this,
                                                VoiceCallActivity.class)
                                                .putExtra("username",
                                                        toChatUsername)
                                                .putExtra("avatar",
                                                        toChatUserAvatar)
                                                .putExtra("nickname",
                                                        toChatUserNick)

                                                .putExtra("isComingCall", false));
                                    } else {
                                        if (UserService.getCurrentUser()
                                                .getBalance() < toUser
                                                .getPrice()) {
                                            // 余额不足
                                            final MyAlertDialog dialog = new MyAlertDialog(
                                                    ChatActivity.this)
                                                    .builder()
                                                    .setTitle("余额不足")
                                                    .setMsg("您的账户余额不足，请充值后再打电话吧！")
                                                    .setNegativeButton(
                                                            "取消",
                                                            new OnClickListener() {
                                                                @Override
                                                                public void onClick(
                                                                        View v) {

                                                                }
                                                            });
                                            dialog.setPositiveButton("确定",
                                                    new OnClickListener() {
                                                        @Override
                                                        public void onClick(
                                                                View v) {
                                                            Intent intent = new Intent(
                                                                    ChatActivity.this,
                                                                    Recharge.class);
                                                            startActivity(intent);

                                                        }
                                                    });
                                            dialog.show();
                                        } else {
                                            if (toUser.getType() == C.USER_TYPE_LOVER) {
                                                charge = 0.2;
                                            } else if (toUser.getType() == C.USER_TYPE_RECOMMENDED) {
                                                charge = 0.2;
                                            }
                                            final MyAlertDialog dialog = new MyAlertDialog(
                                                    ChatActivity.this)
                                                    .builder()
                                                    .setTitle("提示")
                                                    .setMsg("电话额外消耗"
                                                            + (int) (charge * 10)
                                                            + "时光/分钟，是否继续？")
                                                    .setNegativeButton(
                                                            "取消",
                                                            new OnClickListener() {
                                                                @Override
                                                                public void onClick(
                                                                        View v) {

                                                                }
                                                            });
                                            dialog.setPositiveButton("确定",
                                                    new OnClickListener() {
                                                        @Override
                                                        public void onClick(
                                                                View v) {
                                                            startActivity(new Intent(
                                                                    ChatActivity.this,
                                                                    VoiceCallActivity.class)
                                                                    .putExtra(
                                                                            "username",
                                                                            toChatUsername)
                                                                    .putExtra(
                                                                            "avatar",
                                                                            toChatUserAvatar)

                                                                    .putExtra(
                                                                            "nickname",
                                                                            toChatUserNick)
                                                                    .putExtra(
                                                                            "charge",
                                                                            charge)
                                                                    .putExtra(
                                                                            "isComingCall",
                                                                            false));
                                                        }
                                                    });
                                            dialog.show();
                                        }
                                    }
                                } else {
                                    ToolKits.toast(ChatActivity.this, "请检查网络");
                                }

                            }
                        });
            }

        } else if (id == R.id.btn_screct) {// 点击私密消息图标
            //TODO 跳到选择礼物的地方
            Intent giftIntent = new Intent(this, GiftStore.class);
            giftIntent.putExtra("nickName", toChatUserNick);
            giftIntent.putExtra("toUserId", toChatUsername);
            startActivityForResult(giftIntent, REQUEST_CODE_SELECT_GIFT);
        } else if (id == R.id.btn_poke) { // 点击戳一下ta图标

        } else if (id == R.id.btn_sleep) { // 点击我睡了图标
            // if (!EMChatManager.getInstance().isConnected())
            // Toast.makeText(this, st1, 0).show();
            // else
            // startActivity(new Intent(ChatActivity.this,
            // VoiceCallActivity.class).putExtra("username", toChatUsername)
            // .putExtra("isComingCall", false));
        } else if (id == R.id.btn_truth_or_brave) { // 真心话大冒险
            // if (!EMChatManager.getInstance().isConnected())
            // Toast.makeText(this, st1, 0).show();
            // else
            // startActivity(new Intent(this,
            // VideoCallActivity.class).putExtra("username", toChatUsername)
            // .putExtra("isComingCall", false));
        }
    }

    /**
     * 照相获取图片
     */
    public void selectPicFromCamera() {
        if (!CommonUtils.isExitsSdcard()) {
            String st = getResources().getString(
                    R.string.sd_card_does_not_exist);
            Toast.makeText(getApplicationContext(), st, 0).show();
            return;
        }

        cameraFile = new File(PathUtil.getInstance().getImagePath(),
                MLApplication.getInstance().getUserName()
                        + System.currentTimeMillis() + ".jpg");
        cameraFile.getParentFile().mkdirs();
        startActivityForResult(
                new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(
                        MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
                REQUEST_CODE_CAMERA);
    }

    /**
     * 选择文件
     */
    private void selectFileFromLocal() {
        Intent intent = null;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);

        } else {
            intent = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_SELECT_FILE);
    }

    /**
     * 从图库获取图片
     */
    public void selectPicFromLocal() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");

        } else {
            intent = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_LOCAL);
    }

    public void checkOnlineAndSendSns(final String id, final int type) {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", id);
        AVCloud.callFunctionInBackground("checkOnlineStatus", params,
                new FunctionCallback<String>() {

                    @Override
                    public void done(String status, AVException e) {
                        if (e == null) {
                            // 如果不在线需要发短信
                            Log.e("status", status);
                            if (status.equals("offline")) {
                                AVQuery<MLUser> query = new AVQuery<MLUser>(
                                        "_User");
                                query.getInBackground(id,
                                        new GetCallback<MLUser>() {

                                            @Override
                                            public void done(MLUser user,
                                                             AVException e) {
                                                if (e == null) {
                                                    if (user.getNotifyPhone() != null) {
                                                        Map<String, Object> params1 = new HashMap<String, Object>();
                                                        Log.e("status",
                                                                user.getNotifyPhone());
                                                        params1.put(
                                                                "phone",
                                                                user.getNotifyPhone());
                                                        params1.put("type",
                                                                type);
                                                        params1.put("name",
                                                                fromChatUserNick);
                                                        AVCloud.callFunctionInBackground(
                                                                "sendSysSms",
                                                                params1, null);

                                                    }

                                                }
                                            }
                                        });
                            }
                        }
                    }

                });

    }

    public void checkSendStatus() {
        // 判断是否是新的试聊，如果是，要创建试聊记录并回复
        // 如果自己是申请者，那么第一条消息后要创建记录
        if (isSponsNewTestOrder == true) {
            isSponsNewTestOrder = false;
            final MLTestOrder testorder = new MLTestOrder();
            MLUser sponor = new MLUser();
            sponor.setObjectId(fromChatUsername);
            MLUser winner = new MLUser();
            winner.setObjectId(toChatUsername);
            testorder.setSponsor(sponor);
            testorder.setWinner(winner);
            testorder.setStatus(C.ORDER_SATAUS_WAITING);
            testorder.saveInBackground(new SaveCallback() {

                @Override
                public void done(AVException e) {
                    if (e == null) {
                        curTestOrder = testorder;
                        curTestOrerId = testorder.getObjectId();
                        // 把对方添加到自己的试聊
                        MLCache.saveTestOrderUserId(toChatUsername);
                        MolianContactManager.getInstance().saveNewGrayMsg(
                                toChatUsername, toChatUserNick,
                                C.GRAY_MEG_NORMAL_FIRST, "");
                        initTimer(testOrderTime, false);
                        adapter.refreshSelectLast();
                        checkOnlineAndSendSns(toChatUsername, 0);//发短信
                    } else {
                        // 若创建失败，则可以再次创建
                        isSponsNewTestOrder = true;
                    }
                }
            });
        } else if (isWinnerNewOrder) {
            isWinnerNewOrder = false;
            // 获取网络时间
            AVCloud.callFunctionInBackground("getNetTime", null,
                    new FunctionCallback<Long>() {

                        @Override
                        public void done(Long time, AVException e) {
                            if (e == null) {
                                Date date = new Date(time);
                                MLOrder order = new MLOrder();
                                order.setObjectId(curOrderId);
                                order.setStartTime(date);
                                order.setStatus(C.ORDER_SATAUS_GOING);
                                order.saveInBackground(new SaveCallback() {

                                    @Override
                                    public void done(AVException e) {
                                        if (e == null) {
                                            // 这里应该 有一个透传告知对方时间已经开始
                                            // 发一条透传告知对方时间已经开始，并开始初始化时间
                                            MolianContactManager
                                                    .getInstance()
                                                    .sendCMDMsg_ADDOrderId(
                                                            curOrderId,
                                                            fromChatUserNick,
                                                            toChatUsername,
                                                            C.ACTION_ORDER_LOVER_REPLAY,
                                                            null);
                                            // 开始倒计时
                                            freshOrderAndiniTimer(true);

                                        } else {
                                            isWinnerNewOrder = true;

                                        }

                                    }
                                });

                            } else {
                                isWinnerNewOrder = true;
                            }

                        }
                    });

        } else if (isWinnerNewTestOrder) {
            // 获取网络时间
            AVCloud.callFunctionInBackground("getNetTime", null,
                    new FunctionCallback<Long>() {

                        @Override
                        public void done(Long time, AVException e) {
                            if (e == null) {

                                Date date = new Date(time);
                                MLTestOrder testorder = new MLTestOrder();
                                testorder.setObjectId(curTestOrerId);
                                testorder.setStartTime(date);
                                testorder.setStatus(C.ORDER_SATAUS_GOING);
                                testorder.saveInBackground(new SaveCallback() {

                                    @Override
                                    public void done(AVException e) {
                                        // 保存对方到自己的试聊记录
                                        // 将条件改为false，防止每次判断
                                        isWinnerNewTestOrder = false;
                                        // 保存一条本地消息，提示恋爱体验师
                                        MolianContactManager
                                                .getInstance()
                                                .saveNewGrayMsg(toChatUsername,
                                                        toChatUserNick,
                                                        C.GRAY_MEG_LOVER_REPPLY, "");
                                        adapter.refreshSelectLast();
                                        // 发一条透传告知对方时间已经开始，并开始初始化时间
                                        MolianContactManager
                                                .getInstance()
                                                .sendCMDMsg_ADDOrderId(
                                                        curTestOrerId,
                                                        fromChatUserNick,
                                                        toChatUsername,
                                                        C.ACTION_TESTORDER_LOVER_REPLAY,
                                                        null);
                                        // 开始倒计时
                                        initTimer(testOrderTime, true);

                                    }
                                });
                            }
                        }
                    });

        } else if (isSponsNewOrder) {

        }
    }


    /**
     * 发送礼物消息
     */
    private void sendGift(String giftName, String giftInfo, String giftImg) {

        EMMessage message = EMMessage
                .createSendMessage(EMMessage.Type.TXT);
        String content = "送你一个礼物”" + giftName + "”";
        TextMessageBody txtBody = new TextMessageBody(content);
        message.setAttribute("giftType", C.EMMESSAGE_EXT_TYPE_GIFT_MSG);
        message.setAttribute("giftImg", giftImg);
        message.setAttribute("giftName", giftName);
        message.setAttribute("giftInfo", giftInfo);
        // 设置消息body
        message.addBody(txtBody);
        // 设置要发给谁,用户username或者群聊groupid
        message.setReceipt(toChatUsername);
        // 把messgage加到conversation中
        conversation.addMessage(message);
        // 通知adapter有消息变动，adapter会根据加入的这条message显示消息和调用sdk的发送方法
        adapter.refreshSelectLast();
        setResult(RESULT_OK);
        // check发送状态，是否要发送一些提示
//        checkSendStatus();


    }

    /**
     * 发送文本消息
     *
     * @param content  message content
     * @param isResend boolean resend
     */
    private void sendText(String content) {
        if (isNetWorkEnable == false) {
            ToolKits.toast(ChatActivity.this, "网络有点慢哦");
        }
        if (hasTestOrderChance == false && messageEnable == false
                && hasTestOrderChanceWithHer == true) {
            alertBuyDailog(PLANETS, costGold, "每天1次的试聊机会已经用完，领走恋人才可以继续聊天哦");
        } else if (messageEnable == false && hasTestOrderChanceWithHer == false
                && UserService.getCurrentUser().getType() == C.USER_TYPE_NORMAL) {
            ToolKits.toast(ChatActivity.this, "聊天时间已到，快去领走Ta吧");
            rlTimeCutDown.setVisibility(View.VISIBLE);
        } else if (messageEnable == false && hasTestOrderChanceWithHer == false
                && UserService.getCurrentUser().getType() != C.USER_TYPE_NORMAL) {
            ToolKits.toast(ChatActivity.this, "聊天时间已到");
            rlTimeCutDown.setVisibility(View.VISIBLE);
        } else if (messageEnable == false && isLoverToNoraml == true) {
            ToolKits.toast(ChatActivity.this, "口袋恋人不能主动找实习恋人聊天哦");
        } else if (messageEnable == false) {
            // ToolKits.toast(ChatActivity.this, "聊天时间已到");
            rlTimeCutDown.setVisibility(View.VISIBLE);
        } else {
            if (content.length() > 0) {
                EMMessage message = EMMessage
                        .createSendMessage(EMMessage.Type.TXT);
                // 如果是群聊，设置chattype,默认是单聊
                if (chatType == CHATTYPE_GROUP)
                    message.setChatType(ChatType.GroupChat);
                TextMessageBody txtBody = new TextMessageBody(content);
                // 设置消息body
                message.addBody(txtBody);
                // 设置要发给谁,用户username或者群聊groupid
                message.setReceipt(toChatUsername);
                // 把messgage加到conversation中
                conversation.addMessage(message);
                // 通知adapter有消息变动，adapter会根据加入的这条message显示消息和调用sdk的发送方法
                adapter.refreshSelectLast();
                mEditTextContent.setText("");

                setResult(RESULT_OK);

                // check发送状态，是否要发送一些提示
                checkSendStatus();

            }

        }

    }

    /**
     * 发送语音
     *
     * @param filePath
     * @param fileName
     * @param length
     * @param isResend
     */
    private void sendVoice(String filePath, String fileName, String length,
                           boolean isResend) {
        if (isNetWorkEnable == false) {
            ToolKits.toast(ChatActivity.this, "网络有点慢哦");
        }
        if (hasTestOrderChance == false && messageEnable == false
                && hasTestOrderChanceWithHer == true) {
            alertBuyDailog(PLANETS, costGold, "每天1次的试聊机会已经用完，领走恋人才可以继续聊天哦");
        } else if (messageEnable == false && hasTestOrderChanceWithHer == false
                && UserService.getCurrentUser().getType() == C.USER_TYPE_NORMAL) {
            ToolKits.toast(ChatActivity.this, "聊天时间已到，快去领走Ta吧");
            rlTimeCutDown.setVisibility(View.VISIBLE);
        } else if (messageEnable == false && hasTestOrderChanceWithHer == false
                && UserService.getCurrentUser().getType() != C.USER_TYPE_NORMAL) {
            ToolKits.toast(ChatActivity.this, "聊天时间已到");
            // rlTimeCutDown.setVisibility(View.VISIBLE);
        } else if (messageEnable == false) {
            // ToolKits.toast(ChatActivity.this, "聊天时间已到");
            rlTimeCutDown.setVisibility(View.VISIBLE);

        } else {
            if (!(new File(filePath).exists())) {
                return;
            }
            try {
                final EMMessage message = EMMessage
                        .createSendMessage(EMMessage.Type.VOICE);
                // 如果是群聊，设置chattype,默认是单聊
                if (chatType == CHATTYPE_GROUP)
                    message.setChatType(ChatType.GroupChat);
                message.setReceipt(toChatUsername);
                int len = Integer.parseInt(length);
                VoiceMessageBody body = new VoiceMessageBody(
                        new File(filePath), len);
                message.addBody(body);

                conversation.addMessage(message);
                adapter.refreshSelectLast();
                setResult(RESULT_OK);
                // send file
                // sendVoiceSub(filePath, fileName, message);
            } catch (Exception e) {
                e.printStackTrace();
            }

            // check发送状态，是否要发送一些提示
            checkSendStatus();

        }
    }

    /**
     * 发送图片
     *
     * @param filePath
     */
    private void sendPicture(final String filePath) {
        if (isNetWorkEnable == false) {
            ToolKits.toast(ChatActivity.this, "网络有点慢哦");
        }
        if (hasTestOrderChance == false && messageEnable == false
                && hasTestOrderChanceWithHer == true) {
            alertBuyDailog(PLANETS, costGold, "每天1次的试聊机会已经用完，领走恋人才可以继续聊天哦");
        } else if (messageEnable == false && hasTestOrderChanceWithHer == false
                && UserService.getCurrentUser().getType() == C.USER_TYPE_NORMAL) {
            ToolKits.toast(ChatActivity.this, "聊天时间已到，快去领走Ta吧");
            rlTimeCutDown.setVisibility(View.VISIBLE);
        } else if (messageEnable == false && hasTestOrderChanceWithHer == false
                && UserService.getCurrentUser().getType() != C.USER_TYPE_NORMAL) {
            // ToolKits.toast(ChatActivity.this, "聊天时间已到");
            rlTimeCutDown.setVisibility(View.VISIBLE);
        } else if (messageEnable == false) {
            // ToolKits.toast(ChatActivity.this, "聊天时间已到");
            rlTimeCutDown.setVisibility(View.VISIBLE);
        } else {
            String to = toChatUsername;
            // create and add image message in view
            final EMMessage message = EMMessage
                    .createSendMessage(EMMessage.Type.IMAGE);
            // 如果是群聊，设置chattype,默认是单聊
            if (chatType == CHATTYPE_GROUP)
                message.setChatType(ChatType.GroupChat);

            message.setReceipt(to);
            ImageMessageBody body = new ImageMessageBody(new File(filePath));
            // 默认超过100k的图片会压缩后发给对方，可以设置成发送原图
            // body.setSendOriginalImage(true);
            message.addBody(body);
            conversation.addMessage(message);

            listView.setAdapter(adapter);
            adapter.refreshSelectLast();
            setResult(RESULT_OK);
            // more(more);

            // check发送状态，是否要发送一些提示
            checkSendStatus();

        }

    }

    /**
     * 发送视频消息
     */
    private void sendVideo(final String filePath, final String thumbPath,
                           final int length) {
        final File videoFile = new File(filePath);
        if (!videoFile.exists()) {
            return;
        }
        try {
            EMMessage message = EMMessage
                    .createSendMessage(EMMessage.Type.VIDEO);
            // 如果是群聊，设置chattype,默认是单聊
            if (chatType == CHATTYPE_GROUP)
                message.setChatType(ChatType.GroupChat);
            String to = toChatUsername;
            message.setReceipt(to);
            VideoMessageBody body = new VideoMessageBody(videoFile, thumbPath,
                    length, videoFile.length());
            message.addBody(body);
            conversation.addMessage(message);
            listView.setAdapter(adapter);
            adapter.refreshSelectLast();
            setResult(RESULT_OK);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 根据图库图片uri发送图片
     *
     * @param selectedImage
     */
    private void sendPicByUri(Uri selectedImage) {
        if (isNetWorkEnable == false) {
            ToolKits.toast(ChatActivity.this, "网络有点慢哦");
        }
        if (hasTestOrderChance == false && messageEnable == false
                && hasTestOrderChanceWithHer == true) {
            alertBuyDailog(PLANETS, costGold, "每天1次的试聊机会已经用完，领走恋人才可以继续聊天哦");
        } else if (messageEnable == false && hasTestOrderChanceWithHer == false
                && UserService.getCurrentUser().getType() == C.USER_TYPE_NORMAL) {
            ToolKits.toast(ChatActivity.this, "聊天时间已到，快去领走Ta吧");
            rlTimeCutDown.setVisibility(View.VISIBLE);
        } else if (messageEnable == false && hasTestOrderChanceWithHer == false
                && UserService.getCurrentUser().getType() != C.USER_TYPE_NORMAL) {
            // ToolKits.toast(ChatActivity.this, "聊天时间已到");
            rlTimeCutDown.setVisibility(View.VISIBLE);
        } else if (messageEnable == false) {
            // ToolKits.toast(ChatActivity.this, "聊天时间已到");
            rlTimeCutDown.setVisibility(View.VISIBLE);
        } else {
            // String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage, null,
                    null, null, null);
            String st8 = getResources().getString(R.string.cant_find_pictures);
            if (cursor != null) {
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex("_data");
                String picturePath = cursor.getString(columnIndex);
                cursor.close();
                cursor = null;

                if (picturePath == null || picturePath.equals("null")) {
                    Toast toast = Toast.makeText(this, st8, Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                    return;
                }
                sendPicture(picturePath);
            } else {
                File file = new File(selectedImage.getPath());
                if (!file.exists()) {
                    Toast toast = Toast.makeText(this, st8, Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                    return;

                }
                sendPicture(file.getAbsolutePath());
            }

            // check发送状态，是否要发送一些提示
            checkSendStatus();

        }

    }

    /**
     * 发送位置信息
     *
     * @param latitude
     * @param longitude
     * @param imagePath
     * @param locationAddress
     */
    private void sendLocationMsg(double latitude, double longitude,
                                 String imagePath, String locationAddress) {
        EMMessage message = EMMessage
                .createSendMessage(EMMessage.Type.LOCATION);
        // 如果是群聊，设置chattype,默认是单聊
        if (chatType == CHATTYPE_GROUP)
            message.setChatType(ChatType.GroupChat);
        LocationMessageBody locBody = new LocationMessageBody(locationAddress,
                latitude, longitude);
        message.addBody(locBody);
        message.setReceipt(toChatUsername);
        conversation.addMessage(message);
        listView.setAdapter(adapter);
        adapter.refreshSelectLast();
        setResult(RESULT_OK);

    }

    /**
     * 发送文件
     *
     * @param uri
     */
    private void sendFile(Uri uri) {
        String filePath = null;
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {"_data"};
            Cursor cursor = null;

            try {
                cursor = getContentResolver().query(uri, projection, null,
                        null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    filePath = cursor.getString(column_index);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            filePath = uri.getPath();
        }
        File file = new File(filePath);
        if (file == null || !file.exists()) {
            String st7 = getResources().getString(R.string.File_does_not_exist);
            Toast.makeText(getApplicationContext(), st7, 0).show();
            return;
        }
        if (file.length() > 10 * 1024 * 1024) {
            String st6 = getResources().getString(
                    R.string.The_file_is_not_greater_than_10_m);
            Toast.makeText(getApplicationContext(), st6, 0).show();
            return;
        }

        // 创建一个文件消息
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.FILE);
        // 如果是群聊，设置chattype,默认是单聊
        if (chatType == CHATTYPE_GROUP)
            message.setChatType(ChatType.GroupChat);

        message.setReceipt(toChatUsername);
        // add message body
        NormalFileMessageBody body = new NormalFileMessageBody(new File(
                filePath));
        message.addBody(body);
        conversation.addMessage(message);
        listView.setAdapter(adapter);
        adapter.refreshSelectLast();
        setResult(RESULT_OK);
    }

    /**
     * 重发消息
     */
    private void resendMessage() {
        if (messageEnable == false) {
            ToolKits.toast(ChatActivity.this, "暂无法发送，网络慢或聊天时间已到");
            return;
        }

        EMMessage msg = null;
        msg = conversation.getMessage(resendPos);
        // msg.setBackSend(true);
        msg.status = EMMessage.Status.CREATE;

        adapter.refreshSeekTo(resendPos);
    }

    /**
     * 显示语音图标按钮
     *
     * @param view
     */
    public void setModeVoice(final View view) {

        hideKeyboard();
        edittext_layout.setVisibility(View.GONE);
        more.setVisibility(View.GONE);
        view.setVisibility(View.GONE);
        buttonSetModeKeyboard.setVisibility(View.VISIBLE);
        buttonSend.setVisibility(View.GONE);

        buttonPressToSpeak.setVisibility(View.VISIBLE);
        iv_emoticons_normal.setVisibility(View.VISIBLE);
        iv_emoticons_checked.setVisibility(View.INVISIBLE);
        btnContainer.setVisibility(View.VISIBLE);
        emojiIconContainer.setVisibility(View.GONE);

    }

    /**
     * 显示键盘图标
     *
     * @param view
     */
    public void setModeKeyboard(View view) {
        edittext_layout.setVisibility(View.VISIBLE);
        call_content.setVisibility(View.GONE);
        rl_bottom.setVisibility(View.VISIBLE);
        more.setVisibility(View.GONE);
        view.setVisibility(View.GONE);
        buttonSetModeVoice.setVisibility(View.VISIBLE);
        mEditTextContent.requestFocus();
        buttonPressToSpeak.setVisibility(View.GONE);
        if (TextUtils.isEmpty(mEditTextContent.getText())) {

            buttonSend.setVisibility(View.GONE);
        } else {

            buttonSend.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 点击清空聊天记录
     *
     * @param view
     */
    public void emptyHistory(View view) {
        String st5 = getResources().getString(
                R.string.Whether_to_empty_all_chats);
        startActivityForResult(
                new Intent(this, AlertDialog.class)
                        .putExtra("titleIsCancel", true).putExtra("msg", st5)
                        .putExtra("cancel", true), REQUEST_CODE_EMPTY_HISTORY);
    }

    /**
     * 点击进入群组详情
     *
     * @param view
     */
    public void toGroupDetails(View view) {
        // if(group == null){
        // Toast.makeText(getApplicationContext(), R.string.gorup_not_found,
        // 0).show();
        // return;
        // }
        // startActivityForResult((new Intent(this,
        // GroupDetailsActivity.class).putExtra("groupId", toChatUsername)),
        // REQUEST_CODE_GROUP_DETAIL);
    }

    /**
     * 显示或隐藏图标按钮页
     *
     * @param view
     */
    public void more(View view) {
        if (more.getVisibility() == View.GONE) {
            hideKeyboard();
            more.setVisibility(View.VISIBLE);
            btnContainer.setVisibility(View.VISIBLE);
            emojiIconContainer.setVisibility(View.GONE);

        } else {
            if (emojiIconContainer.getVisibility() == View.VISIBLE) {
                emojiIconContainer.setVisibility(View.GONE);
                btnContainer.setVisibility(View.VISIBLE);
                iv_emoticons_normal.setVisibility(View.VISIBLE);
                iv_emoticons_checked.setVisibility(View.INVISIBLE);
            } else {
                more.setVisibility(View.GONE);
            }
        }

    }

    /**
     * 显示聊天界面
     *
     * @param view
     */
    public void shwoChatContent(View view) {

        call_content.setVisibility(View.GONE);
        rl_bottom.setVisibility(View.VISIBLE);
    }

    /**
     * 显示打电话界面
     *
     * @param view
     */
    public void showCallContent(View view) {
        // hideKeyboard();
        // call_content.setVisibility(View.VISIBLE);
        // rl_bottom.setVisibility(View.GONE);
        // btnContainer.setVisibility(View.GONE);
        // if (emojiIconContainer.getVisibility() == View.VISIBLE) {
        // emojiIconContainer.setVisibility(View.GONE);
        // btnContainer.setVisibility(View.GONE);
        // iv_emoticons_normal.setVisibility(View.VISIBLE);
        // iv_emoticons_checked.setVisibility(View.INVISIBLE);
        // } else {
        // more.setVisibility(View.GONE);
        // }
        // 点击打电话图标
        AVAnalytics.onEvent(ChatActivity.this, "聊天页打电话");

        String st1 = getResources().getString(R.string.not_connect_to_server);
        try {
            if (isNetWorkEnable == false) {
                ToolKits.toast(ChatActivity.this, "网络有点慢哦");
                return;
            }
            if (isTestOrderGoing == true) {
                ToolKits.toast(ChatActivity.this, "试聊时不可以打电话哦");
                return;
            } else if (callEnalbe == false
                    && touser.getInt("type") == C.USER_TYPE_NORMAL
                    && UserService.getCurrentUser().getType() == C.USER_TYPE_NORMAL) {
                ToolKits.toast(ChatActivity.this, "暂无法通话，你们还不是恋人，点击右上角加为恋人吧");
                return;
            }
            if (callEnalbe == false && isAllLoverTestOrderSponsor == true) {
                ToolKits.toast(ChatActivity.this, "试聊时不可以打电话哦");
                return;
            } else if (messageEnable == true
                    && UserService.getCurrentUser().getType() != C.USER_TYPE_NORMAL
                    && isOrderGoing == false && isAllLoverOrderSponsor == false) {
                ToolKits.toast(ChatActivity.this, "你要回复后才可以打电话哦");
                // rlTimeCutDown.setVisibility(View.VISIBLE);
                return;
            } else if (messageEnable == true
                    && touser.getInt("type") != C.USER_TYPE_NORMAL
                    && isOrderGoing == false && isAllLoverOrderSponsor == true) {
                ToolKits.toast(ChatActivity.this, "要等对方回复后才可以打电话哦");
                // rlTimeCutDown.setVisibility(View.VISIBLE);
                return;
            } else if (callEnalbe == false && isAllLoverOrderSponsor == false
                    && isAllLover == true) {
                ToolKits.toast(ChatActivity.this, "暂无法通话，聊天时间已到");
                return;
            } else if (callEnalbe == false
                    && touser.getInt("type") != C.USER_TYPE_NORMAL
                    && isSponsNewOrder) {
                ToolKits.toast(ChatActivity.this, "要等对方回复后才可以打电话哦");
                // rlTimeCutDown.setVisibility(View.VISIBLE);
                return;
            } else if (messageEnable == true
                    && UserService.getCurrentUser().getType() != C.USER_TYPE_NORMAL
                    && isOrderGoing == false) {
                ToolKits.toast(ChatActivity.this, "你要回复后才可以打电话哦");
                // rlTimeCutDown.setVisibility(View.VISIBLE);
                return;
            } else if (callEnalbe == false
                    && touser.getInt("type") != C.USER_TYPE_NORMAL) {
                ToolKits.toast(ChatActivity.this, "点击右上角领走恋人才可以打电话哦");
                // rlTimeCutDown.setVisibility(View.VISIBLE);
                return;
            } else if (messageEnable == false && isLoverToNoraml == true) {
                ToolKits.toast(ChatActivity.this, "口袋恋人不能主动找实习恋人聊天哦");
                return;
            } else if (callEnalbe == false) {
                ToolKits.toast(ChatActivity.this, "暂无法通话，聊天时间已到");
                return;
            }
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();

        }
        if (!EMChatManager.getInstance().isConnected()) {
            Toast.makeText(this, st1, 0).show();
        } else {
            AVQuery<MLUser> query = new AVQuery<MLUser>("_User");
            query.getInBackground(toChatUsername, new GetCallback<MLUser>() {

                @Override
                public void done(MLUser user, AVException e) {
                    if (e == null) {
                        toUser = user;
                        if (UserService.getCurrentUser().getType() != C.USER_TYPE_NORMAL
                                && (toUser.getType() == C.USER_TYPE_NORMAL || (isAllLover == true && isAllLoverOrderSponsor == false))) {
                            final MyAlertDialog dialog = new MyAlertDialog(
                                    ChatActivity.this)
                                    .builder()
                                    .setTitle("提示")
                                    .setMsg("主动给对方打电话免费哦")
                                    .setNegativeButton("取消",
                                            new OnClickListener() {
                                                @Override
                                                public void onClick(View v) {

                                                }
                                            });
                            dialog.setPositiveButton("确定",
                                    new OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            startActivity(new Intent(
                                                    ChatActivity.this,
                                                    VoiceCallActivity.class)
                                                    .putExtra("username",
                                                            toChatUsername)
                                                    .putExtra("avatar",
                                                            toChatUserAvatar)

                                                    .putExtra("nickname",
                                                            toChatUserNick)
                                                    .putExtra("isComingCall",
                                                            false));
                                        }
                                    });
                            dialog.show();
                        } else if (user.getType() == C.USER_TYPE_NORMAL
                                || (isAllLover == true && isAllLoverOrderSponsor == false)) {
                            startActivity(new Intent(ChatActivity.this,
                                    VoiceCallActivity.class)
                                    .putExtra("username", toChatUsername)
                                    .putExtra("avatar", toChatUserAvatar)
                                    .putExtra("nickname", toChatUserNick)

                                    .putExtra("isComingCall", false));
                        } else {
                            if (UserService.getCurrentUser().getBalance() < toUser
                                    .getPrice()) {
                                // 余额不足
                                final MyAlertDialog dialog = new MyAlertDialog(
                                        ChatActivity.this)
                                        .builder()
                                        .setTitle("余额不足")
                                        .setMsg("您的账户余额不足，请充值后再打电话吧！")
                                        .setNegativeButton("取消",
                                                new OnClickListener() {
                                                    @Override
                                                    public void onClick(View v) {

                                                    }
                                                });
                                dialog.setPositiveButton("确定",
                                        new OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                Intent intent = new Intent(
                                                        ChatActivity.this,
                                                        Recharge.class);
                                                startActivity(intent);

                                            }
                                        });
                                dialog.show();
                            } else {
                                if (toUser.getType() == C.USER_TYPE_LOVER) {
                                    charge = 0.2;
                                } else if (toUser.getType() == C.USER_TYPE_RECOMMENDED) {
                                    charge = 0.2;
                                }
                                final MyAlertDialog dialog = new MyAlertDialog(
                                        ChatActivity.this)
                                        .builder()
                                        .setTitle("提示")
                                        .setMsg("电话额外消耗" + (int) (charge * 10)
                                                + "时光/分钟，是否继续？")
                                        .setNegativeButton("取消",
                                                new OnClickListener() {
                                                    @Override
                                                    public void onClick(View v) {

                                                    }
                                                });
                                dialog.setPositiveButton("确定",
                                        new OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                startActivity(new Intent(
                                                        ChatActivity.this,
                                                        VoiceCallActivity.class)
                                                        .putExtra("username",
                                                                toChatUsername)
                                                        .putExtra("avatar",
                                                                toChatUserAvatar)

                                                        .putExtra("nickname",
                                                                toChatUserNick)
                                                        .putExtra("charge",
                                                                charge)
                                                        .putExtra(
                                                                "isComingCall",
                                                                false));
                                            }
                                        });
                                dialog.show();
                            }
                        }
                    } else {
                        ToolKits.toast(ChatActivity.this, "请检查网络");
                    }

                }
            });
        }
    }

    /**
     * 点击文字输入框
     *
     * @param v
     */
    public void editClick(View v) {
        listView.setSelection(listView.getCount() - 1);
        if (more.getVisibility() == View.VISIBLE) {
            more.setVisibility(View.GONE);
            iv_emoticons_normal.setVisibility(View.VISIBLE);
            iv_emoticons_checked.setVisibility(View.INVISIBLE);
        }

    }

    /**
     * 消息广播接收者
     */
    private class NewMessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 记得把广播给终结掉
            abortBroadcast();

            String username = intent.getStringExtra("from");
            String msgid = intent.getStringExtra("msgid");
            // 收到这个广播的时候，message已经在db和内存里了，可以通过id获取mesage对象
            EMMessage message = EMChatManager.getInstance().getMessage(msgid);
            // 如果是群聊消息，获取到group id
            if (message.getChatType() == ChatType.GroupChat) {
                username = message.getTo();
            }
            if (!username.equals(toChatUsername)) {
                // 消息不是发给当前会话，return
                notifyNewMessage(message);
                return;
            }
            // conversation =
            // EMChatManager.getInstance().getConversation(toChatUsername);
            // 通知adapter有新消息，更新ui
            adapter.refresh();
            listView.setSelection(listView.getCount() - 1);

        }
    }

    /**
     * 消息回执BroadcastReceiver
     */
    private BroadcastReceiver ackMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            abortBroadcast();
            // Log.e("收到回执", "收到回执");
            String msgid = intent.getStringExtra("msgid");
            String from = intent.getStringExtra("from");
            EMConversation conversation = EMChatManager.getInstance()
                    .getConversation(from);
            if (conversation != null) {
                // 把message设为已读
                EMMessage msg = conversation.getMessage(msgid);
                if (msg != null) {
                    msg.isAcked = true;
                }
            }
            adapter.notifyDataSetChanged();

        }
    };

    /**
     * 消息送达BroadcastReceiver
     */
    private BroadcastReceiver deliveryAckMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            abortBroadcast();

            String msgid = intent.getStringExtra("msgid");
            String from = intent.getStringExtra("from");
            EMConversation conversation = EMChatManager.getInstance()
                    .getConversation(from);
            if (conversation != null) {
                // 把message设为已读
                EMMessage msg = conversation.getMessage(msgid);

                if (msg != null) {
                    msg.isDelivered = true;
                }
            }

            adapter.notifyDataSetChanged();
        }
    };
    private PowerManager.WakeLock wakeLock;

    /**
     * 按住说话listener
     */
    class PressToSpeakListen implements View.OnTouchListener {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if (!CommonUtils.isExitsSdcard()) {
                        String st4 = getResources().getString(
                                R.string.Send_voice_need_sdcard_support);
                        Toast.makeText(ChatActivity.this, st4, Toast.LENGTH_SHORT)
                                .show();
                        return false;
                    }
                    try {
                        v.setPressed(true);
                        wakeLock.acquire();
                        if (VoicePlayClickListener.isPlaying)
                            VoicePlayClickListener.currentPlayListener
                                    .stopPlayVoice();
                        recordingContainer.setVisibility(View.VISIBLE);
                        recordingHint
                                .setText(getString(R.string.move_up_to_cancel));
                        recordingHint.setBackgroundColor(Color.TRANSPARENT);
                        voiceRecorder.startRecording(null, toChatUsername,
                                getApplicationContext());
                    } catch (Exception e) {
                        e.printStackTrace();
                        v.setPressed(false);
                        if (wakeLock.isHeld())
                            wakeLock.release();
                        if (voiceRecorder != null)
                            voiceRecorder.discardRecording();
                        recordingContainer.setVisibility(View.INVISIBLE);
                        Toast.makeText(ChatActivity.this, R.string.recoding_fail,
                                Toast.LENGTH_SHORT).show();
                        return false;
                    }

                    return true;
                case MotionEvent.ACTION_MOVE: {
                    if (event.getY() < 0) {
                        recordingHint
                                .setText(getString(R.string.release_to_cancel));
                        recordingHint
                                .setBackgroundResource(R.drawable.recording_text_hint_bg);
                    } else {
                        recordingHint
                                .setText(getString(R.string.move_up_to_cancel));
                        recordingHint.setBackgroundColor(Color.TRANSPARENT);
                    }
                    return true;
                }
                case MotionEvent.ACTION_UP:
                    v.setPressed(false);
                    recordingContainer.setVisibility(View.INVISIBLE);
                    if (wakeLock.isHeld())
                        wakeLock.release();
                    if (event.getY() < 0) {
                        // discard the recorded audio.
                        voiceRecorder.discardRecording();

                    } else {
                        // stop recording and send voice file
                        String st1 = getResources().getString(
                                R.string.Recording_without_permission);
                        String st2 = getResources().getString(
                                R.string.The_recording_time_is_too_short);
                        String st3 = getResources().getString(
                                R.string.send_failure_please);
                        try {
                            int length = voiceRecorder.stopRecoding();
                            if (length > 0) {
                                sendVoice(voiceRecorder.getVoiceFilePath(),
                                        voiceRecorder
                                                .getVoiceFileName(toChatUsername),
                                        Integer.toString(length), false);
                            } else if (length == EMError.INVALID_FILE) {
                                Toast.makeText(getApplicationContext(), st1,
                                        Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getApplicationContext(), st2,
                                        Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(ChatActivity.this, st3,
                                    Toast.LENGTH_SHORT).show();
                        }

                    }
                    return true;
                default:
                    recordingContainer.setVisibility(View.INVISIBLE);
                    if (voiceRecorder != null)
                        voiceRecorder.discardRecording();
                    return false;
            }
        }
    }

    /**
     * 获取表情的gridview的子view
     *
     * @param i
     * @return
     */
    private View getGridChildView(int i) {
        View view = View.inflate(this, R.layout.expression_gridview, null);
        ExpandGridView gv = (ExpandGridView) view.findViewById(R.id.gridview);
        List<String> list = new ArrayList<String>();
        if (i == 1) {
            List<String> list1 = reslist.subList(0, 20);
            list.addAll(list1);
        } else if (i == 2) {
            list.addAll(reslist.subList(20, reslist.size()));
        }
        list.add("delete_expression");
        final ExpressionAdapter expressionAdapter = new ExpressionAdapter(this,
                1, list);
        gv.setAdapter(expressionAdapter);
        gv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String filename = expressionAdapter.getItem(position);
                try {
                    // 文字输入框可见时，才可输入表情
                    // 按住说话可见，不让输入表情
                    if (buttonSetModeKeyboard.getVisibility() != View.VISIBLE) {

                        if (filename != "delete_expression") { // 不是删除键，显示表情
                            // 这里用的反射，所以混淆的时候不要混淆SmileUtils这个类
                            Class clz = Class
                                    .forName("com.pocketsweet.chatlib.utils.SmileUtils");
                            Field field = clz.getField(filename);
                            mEditTextContent.append(SmileUtils.getSmiledText(
                                    ChatActivity.this, (String) field.get(null)));
                        } else { // 删除文字或者表情
                            if (!TextUtils.isEmpty(mEditTextContent.getText())) {

                                int selectionStart = mEditTextContent
                                        .getSelectionStart();// 获取光标的位置
                                if (selectionStart > 0) {
                                    String body = mEditTextContent.getText()
                                            .toString();
                                    String tempStr = body.substring(0,
                                            selectionStart);
                                    int i = tempStr.lastIndexOf("[");// 获取最后一个表情的位置
                                    if (i != -1) {
                                        CharSequence cs = tempStr.substring(i,
                                                selectionStart);
                                        if (SmileUtils.containsKey(cs
                                                .toString()))
                                            mEditTextContent.getEditableText()
                                                    .delete(i, selectionStart);
                                        else
                                            mEditTextContent.getEditableText()
                                                    .delete(selectionStart - 1,
                                                            selectionStart);
                                    } else {
                                        mEditTextContent.getEditableText()
                                                .delete(selectionStart - 1,
                                                        selectionStart);
                                    }
                                }
                            }

                        }
                    }
                } catch (Exception e) {
                }

            }
        });
        return view;
    }

    public List<String> getExpressionRes(int getSum) {
        List<String> reslist = new ArrayList<String>();
        for (int x = 1; x <= getSum; x++) {
            String filename = "ee_" + x;

            reslist.add(filename);

        }
        return reslist;

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        activityInstance = null;
        // 注销广播
        try {
            unregisterReceiver(headsetPlugReceiver);// 注销耳机插入状态的监听
            unregisterReceiver(receiver);
            receiver = null;
        } catch (Exception e) {
        }
        try {
            unregisterReceiver(ackMessageReceiver);
            ackMessageReceiver = null;
            unregisterReceiver(deliveryAckMessageReceiver);
            deliveryAckMessageReceiver = null;
        } catch (Exception e) {
        }
        countdownTimerChat.stopCountDown();
    }

    @Override
    protected void onResume() {
        mSensorManager.registerListener(this, mSensor,
                SensorManager.SENSOR_DELAY_NORMAL);
        super.onResume();
        if (group != null)
            ((TextView) findViewById(R.id.name)).setText(group.getGroupName());
        adapter.refresh();
    }

    @Override
    protected void onPause() {
        mSensorManager.unregisterListener(this);
        super.onPause();
        if (wakeLock.isHeld())
            wakeLock.release();
        if (VoicePlayClickListener.isPlaying
                && VoicePlayClickListener.currentPlayListener != null) {
            // 停止语音播放
            VoicePlayClickListener.currentPlayListener.stopPlayVoice();
        }

        try {
            // 停止录音
            if (voiceRecorder.isRecording()) {
                voiceRecorder.discardRecording();
                recordingContainer.setVisibility(View.INVISIBLE);
            }
        } catch (Exception e) {
        }
    }

    /**
     * 隐藏软键盘
     */
    private void hideKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                manager.hideSoftInputFromWindow(getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 加入到黑名单
     *
     * @param username
     */
    private void addUserToBlacklist(final String username) {
        final ProgressDialog pd = new ProgressDialog(this);
        pd.setMessage(getString(R.string.Is_moved_into_blacklist));
        pd.setCanceledOnTouchOutside(false);
        pd.show();
        new Thread(new Runnable() {
            public void run() {
                try {
                    EMContactManager.getInstance().addUserToBlackList(username,
                            false);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            Toast.makeText(getApplicationContext(),
                                    R.string.Move_into_blacklist_success, 0)
                                    .show();
                            // 删除与此人的会话
                            EMChatManager.getInstance().deleteConversation(
                                    username);
                            // 关闭页面
                            ChatActivity.activityInstance.finish();
                        }
                    });
                } catch (EaseMobException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            Toast.makeText(getApplicationContext(),
                                    R.string.Move_into_blacklist_failure, 0)
                                    .show();
                        }
                    });
                }
            }
        }).start();
    }

    /**
     * 返回
     *
     * @param view
     */
    public void back(View view) {
        finish();
    }

    // @Override
    // public boolean dispatchTouchEvent(MotionEvent event) {
    // if (null != this.getCurrentFocus()) {
    // /**
    // * 点击空白位置 隐藏time
    // */
    // if (rlTimeCutDown.getVisibility() == View.VISIBLE) {
    // rlTimeCutDown.setVisibility(View.GONE);
    // }
    // }
    // return super.onTouchEvent(event);
    // }

    /**
     * 覆盖手机返回键
     */
    @Override
    public void onBackPressed() {
        if (more.getVisibility() == View.VISIBLE) {
            more.setVisibility(View.GONE);
            iv_emoticons_normal.setVisibility(View.VISIBLE);
            iv_emoticons_checked.setVisibility(View.INVISIBLE);
        } else {
            super.onBackPressed();
        }
    }

    /**
     * listview滑动监听listener
     */
    private class ListScrollListener implements OnScrollListener {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            switch (scrollState) {
                case OnScrollListener.SCROLL_STATE_IDLE:
                    if (view.getFirstVisiblePosition() == 0 && !isloading
                            && haveMoreData) {
                        isloading = true;
                        loadmorePB.setVisibility(View.VISIBLE);
                        // sdk初始化加载的聊天记录为20条，到顶时去db里获取更多
                        List<EMMessage> messages;
                        try {
                            // 获取更多messges，调用此方法的时候从db获取的messages
                            // sdk会自动存入到此conversation中
                            if (chatType == CHATTYPE_SINGLE)
                                messages = conversation.loadMoreMsgFromDB(adapter
                                        .getItem(0).getMsgId(), pagesize);
                            else
                                messages = conversation.loadMoreGroupMsgFromDB(
                                        adapter.getItem(0).getMsgId(), pagesize);
                        } catch (Exception e1) {
                            loadmorePB.setVisibility(View.GONE);
                            return;
                        }
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                        }
                        if (messages.size() != 0) {
                            // 刷新ui
                            if (messages.size() > 0) {
                                adapter.refreshSeekTo(messages.size() - 1);
                            }
                            if (messages.size() != pagesize)
                                haveMoreData = false;
                        } else {
                            haveMoreData = false;
                        }
                        loadmorePB.setVisibility(View.GONE);
                        isloading = false;

                    }
                    break;
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                             int visibleItemCount, int totalItemCount) {

        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        // 点击notification bar进入聊天页面，保证只有一个聊天页面
        String username = intent.getStringExtra("userId");
        if (toChatUsername.equals(username))
            super.onNewIntent(intent);
        else {
            finish();
            startActivity(intent);
        }

    }

    /**
     * 转发消息
     *
     * @param forward_msg_id
     */
    protected void forwardMessage(String forward_msg_id) {
        EMMessage forward_msg = EMChatManager.getInstance().getMessage(
                forward_msg_id);
        EMMessage.Type type = forward_msg.getType();
        switch (type) {
            case TXT:
                // 获取消息内容，发送消息
                String content = ((TextMessageBody) forward_msg.getBody())
                        .getMessage();
                sendText(content);
                break;
            case IMAGE:
                // 发送图片
                String filePath = ((ImageMessageBody) forward_msg.getBody())
                        .getLocalUrl();
                if (filePath != null) {
                    File file = new File(filePath);
                    if (!file.exists()) {
                        // 不存在大图发送缩略图
                        filePath = ImageUtils.getThumbnailImagePath(filePath);
                    }
                    sendPicture(filePath);
                }
                break;
            default:
                break;
        }
    }

    public String getToChatUsername() {
        return toChatUsername;
    }

    public void freshFriendStatus() {
        if (UserService.getCurrentUser().getType() != C.USER_TYPE_NORMAL) {
            ivFriendMore.setVisibility(View.GONE);
        } else {
            ivFriendMore.setVisibility(View.VISIBLE);
        }
        ivMore.setVisibility(View.GONE);
        callEnalbe = true;
    }

    public ListView getListView() {
        return listView;
    }

    // 分手操作
    public void breakup() {
        LayoutInflater inflater = LayoutInflater.from(ChatActivity.this);
        final View applyView = inflater.inflate(R.layout.view_apply, null);
        final EditText etReason = (EditText) applyView
                .findViewById(R.id.etReason);
        etReason.setHint("分手的原因（可以为空）");
        final MyAlertDialog dialog = new MyAlertDialog(ChatActivity.this)
                .builder().setTitle("我要分手").setView(applyView)
                .setNegativeButton("取消", new OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
        dialog.setPositiveButton("确定", new OnClickListener() {
            @Override
            public void onClick(View v) {
                final String reason = etReason.getText().toString();
                AVQuery<MLUser> query = new AVQuery<MLUser>("_User");
                query.getInBackground(toChatUsername,
                        new GetCallback<MLUser>() {

                            @Override
                            public void done(MLUser user, AVException e) {
                                if (e == null) {
                                    MolianContactManager.getInstance()
                                            .deleteFriend(user, reason);
                                    AVAnalytics.onEvent(ChatActivity.this,
                                            "我要分手");
                                } else {
                                    ToolKits.toast(ChatActivity.this,
                                            "发送失败，请检查网络");
                                }
                            }
                        });
            }
        });
        dialog.show();
    }

    /**
     * 重写onKeyDown方法
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (rlTimeCutDown.getVisibility() == View.VISIBLE) {
                rlTimeCutDown.setVisibility(View.GONE);
            } else {
                ChatActivity.this.finish();
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1) {

    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (isHeadSet == true) {
            return;
        }
        float range = event.values[0];
        if (range == mSensor.getMaximumRange()) {
            // Toast.makeText(this, "外放模式", Toast.LENGTH_LONG).show();
            chatOptions.setUseSpeaker(true);
            EMChatManager.getInstance().setChatOptions(chatOptions);
            HXSDKHelper.getInstance().getModel().setSettingMsgSpeaker(true);
            audioManager.setMode(AudioManager.MODE_NORMAL);

            audioManager.setSpeakerphoneOn(true);

        } else {
            // Toast.makeText(this, "听筒模式", Toast.LENGTH_LONG).show();
            chatOptions.setUseSpeaker(false);
            EMChatManager.getInstance().setChatOptions(chatOptions);
            HXSDKHelper.getInstance().getModel().setSettingMsgSpeaker(false);
            audioManager.setMode(AudioManager.MODE_IN_CALL);

            setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
            audioManager.setSpeakerphoneOn(false);// 关闭扬声器
            audioManager.setRouting(AudioManager.MODE_NORMAL,
                    AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL);

        }
        // Log.e("==voice", "voice:" + chatOptions.getUseSpeaker());
    }

}
